user1789630
user1789630

Reputation: 23

SQL add month to a query without calendar table

I have a pretty simple table here:


Table1
ID
Date1
Date2
Date3


I want to summarize the data by month and ID so the query result comes out like this:


Query Result of table1
ID
Month
Count of Date1 from the month that's not null
Count of Date2 from the month that's not null
Count of Date3 from the month that's not null


I currently have this query below that only pulls one month depending on what @month is specified to:

Select ID, @month as [Month]  
Sum((Case When Month(Date1)=@month then 1 else 0 END)) as [Date1 Count],   
Sum((Case When Month(Date2)=@month then 1 else 0 END)) as [Date2 Count],  
Sum((Case When Month(Date3)=@month then 1 else 0 END)) as [Date3 Count],  
From Table1  
Group by ID 

But I want to pull all 12 month, however the database does not have a month table or calendar table, how can I create a query that will include all 12 month for each IDs and get their corresponding monthly counts for Date1, Date2, and Date3? Btw, a lot of the entries have one of the Dates empty, e.g. Date1 and Date3 = Null whereas Date2 = '01/01/2008'. Thanks in advance!

Upvotes: 2

Views: 526

Answers (1)

mellamokb
mellamokb

Reputation: 56769

Since there are only 12 months and that will never change, it's simple enough to use a CTE or subquery to generate the month numbers:

;with M as (
  select 1 as month union
  select 2 union
  select 3 union
  select 4 union
  select 5 union
  select 6 union
  select 7 union
  select 8 union
  select 9 union
  select 10 union
  select 11 union
  select 12
)
Select ID, M.Month,
Sum((Case When Month(Date1)=M.Month then 1 else 0 END)) as [Date1 Count],   
Sum((Case When Month(Date2)=M.Month then 1 else 0 END)) as [Date2 Count],  
Sum((Case When Month(Date3)=M.Month then 1 else 0 END)) as [Date3 Count]  
From M,Table1
Group by ID,M.month

Demo: http://www.sqlfiddle.com/#!3/19ed6b/1

Upvotes: 1

Related Questions