SQL query for Figuring counts by month

后端 未结 2 786
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-13 04:18

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

SELECT
    months???,
    count(whatever1) count1,
    count(whatever2) co         


        
2条回答
  •  爱一瞬间的悲伤
    2021-01-13 04:56

    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
    

提交回复
热议问题