Sunday, 29 September 2013

Get count per year of data with begin and end dates

Get count per year of data with begin and end dates

I have a set of data that lists each employee ever employed in a certain
type of department at many cities, and it lists each employee's begin and
end date.
For example:
name city_id start_date end_date
-----------------------------------------
Joe Public 54 3-19-1994 9-1-2002
Suzi Que 54 10-1-1995 9-1-2005
What I want is each city's employee count for each year in a particular
period. For example, if this was all the data for city 54, then I'd show
this as the query results if I wanted to show city 54's employee count for
the years 1990-2005:
city_id year employee_count
-----------------------------
54 1990 0
54 1991 0
54 1992 0
54 1993 0
54 1994 1
54 1995 2
54 1996 2
54 1997 2
54 1998 2
54 1999 2
54 2000 2
54 2001 2
54 2002 2
54 2003 1
54 2004 1
54 2005 1
(Note that I will have many cities, so the primary key here would be city
and year unless I want to have a separate id column.)
Is there an efficient SQL query to do this? All I can think of is a series
of UNIONed queries, with one query for each year I wanted to get numbers
for.
My dataset has a few hundred cities and 178,000 employee records. I need
to find a few decades' worth of this yearly data for each city on my
dataset.

No comments:

Post a Comment