小编典典

SQL查询按月计算计数

sql

在SQL中按月将一列中的1-12连接到一堆计数的好方法是什么?…在​​SQL中

SELECT
    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???

最终会像

"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

编辑-基本上是一种获取我的月份列表/表格/任何内容的巧妙方法


阅读 156

收藏
2021-03-23

共1个答案

小编典典

许多方法…在上一份工作中对许多应用程序来说对我来说效果很好的一种方法是建立时间表。

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

然后,您可以将其日期字段放在startstamp和endstamp之间的timeframes表中进行联接。

这样可以很容易地拉出某个时间段或所有时间段…

您的记录可能更简单,只需12条记录(即1月1日)并加入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

您也可以临时执行月份操作,如下所示:

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
2021-03-23