- May 27, 2002
- 12,653
- 205
- 106
i need help doing a summary SQL query, with multiple years of aggregates...
So lets say I have 2 tables
I need help writing SQL to summarize all this data in query.
I know the first thing I need to do is select ALL the years...
Select distinct datepart(yyyy,ContractInitiated) As OneYr
From Contracts
and
I know I need to select 3 independent aggregates
Select Count(ContractID) as CT From Contracts
Select Sum(Employees) as Emp From Jobs
Select Sum(Hours) as Hrs From Jobs
But how do I nest these 2 items together so I get the Summary data for each year?
to product this:
So lets say I have 2 tables
Code:
Contracts Table
[ID] [Contractee] [ContractInitated] [ContractExpired]
1 Scott Jan 1 2010 null
2 Bill Jan 1 2010 Jan 1 2011
3 Doug Jan 1 2011 null
4 Mario Jan 1 2011 Jan 1 2012
5 Wendy Jan 1 2012 null
6 Dan Jan 1 2012 Jan 1 2013
(Null in contractExpired, meants the contract is still active)
Jobs Table
[JobID] [ContractID] [Employees] [Hours]
1 1 10 2
2 2 9 3
3 3 8 2
4 4 7 4
5 5 6 2
6 6 5 4
7 1 11 3
8 2 12 2
9 3 13 3
10 4 14 2
11 5 15 1
12 6 10 5
I need help writing SQL to summarize all this data in query.
I know the first thing I need to do is select ALL the years...
Select distinct datepart(yyyy,ContractInitiated) As OneYr
From Contracts
and
I know I need to select 3 independent aggregates
Select Count(ContractID) as CT From Contracts
Select Sum(Employees) as Emp From Jobs
Select Sum(Hours) as Hrs From Jobs
But how do I nest these 2 items together so I get the Summary data for each year?
to product this:
Code:
[Year] [Contracts] [EmployeeCount] [HourTotal]
2010 2 42 10
2011 4 84 21
2012 6 99 28