开发者

SQL query for Figuring counts by month

whats a good way to join 1-12 in a column to a bunch of counts by month?... in SQL

SELE开发者_如何学运维CT
    months???,
    count(whatever1) count1,
    count(whatever2) count2
FROM
    months????
    LEFT JOIN whatever1 ON
        month(whatever1.Date) = months???.monthid
    LEFT JOIN whatever2 ON
        month(whatever2.Date) = months???.monthid
GROUP BY
    months???

something that would end up like

"month","whatever1count","whatever2count"
1,null,5
2,null,3
3,null,null
4,2,3
5,36,73
6,2,null
7,45,944
8,null,12
9,1467,3
10,null,2
11,3,25
12,4,null

edit- basically where is a slick way to get my months list/table/whatever


Many ways... one that worked well for me across many applications at a previous job was to build a table of timeframes.

id - Year - Month   - StartStamp            - End Stamp  
1  - 2008 - January - 1/1/2008 00:00:00.000 - 1/31/2008 23:59:59.999

Then you can just join against the timeframes table where your date field is between startstamp and endstamp.

This makes it easy to pull a certain time period, or all time periods...

Yours could be simpler, with just 12 records (i.e. 1 - January) and joining on DATEPART(m,DateColumn)

select mon.monthNumber, mon.monthName, 
       count(a.*) as count1, count(b.*) as count2
from months mon
left join whatever1 a on DATEPART(m,a.Date) = mon.monthNumber
left join whatever2 b on DATEPART(m,b.Date) = mon.monthNumber
group by mon.monthNumber, mon.monthName

You could also do the month thing ad-hoc, like so:

select mon.monthNumber, mon.monthName, 
       count(a.*) as count1, count(b.*) as count2
from (
   select 1 as monthNumber, 'January' as monthName
   union
   select 2 as monthNumber, 'February' as monthName
   union
   select 3 as monthNumber, 'March' as monthName
   union
   ......etc.....
) mon
left join whatever1 a on DATEPART(m,a.Date) = mon.monthNumber
left join whatever2 b on DATEPART(m,b.Date) = mon.monthNumber
group by mon.monthNumber, mon.monthName


basically where is a slick way to get my months list/table/whatever

You can use a recursive cte to build a list of months.

;with Months(MonthNum) as
(
  select 1 MonthNum
  union all
  select MonthNum+1
  from Months
  where MonthNum < 12 
)

-- Your query goes here
select * 
from Months
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜