如何使用 DATEADD 进行分组以获得想要的结果

How to do Group By with the DATEADD for wanted result

我正在编写一个函数来计算每个月收到的邮件总数。但是使用 Group By DATEADD 函数只能得到非 o 计数值。 我需要获取 0 计数内的所有值。

SELECT (MAX(ReceivedMonthofYear)+' '+MAX(ReceivedYear)) AS MonthStartDate,COUNT(ReceivedDateTime) AS MonthlyTotal 来自 tblMessageReceived GROUP BY DATEADD(month, DATEDIFF(month, 0, ReceivedDateTime), 0)

这导致查询

实际上我想得到给定范围内的所有值的输出,也有 0 个计数值和月份。

谢谢!

SELECT td.monthCol+' '+td.yearCol AS MonthStartDate,
       isnull(MonthlyTotal,0) AS MonthlyTotal
FROM tblDates td
LEFT OUTER JOIN (SELECT (MAX(ReceivedMonthofYear)+' '+MAX(ReceivedYear)) AS MonthStartDate,
                        COUNT(ReceivedDateTime) AS MonthlyTotal 
                 FROM tblMessageReceived 
                 GROUP BY DATEADD(month, DATEDIFF(month, 0, ReceivedDateTime), 0)) tm
 ON (td.monthCol+' '+td.yearCol = tm.MonthStartDate)

试试这个,将 MonthCol 和 YearCol 替换为您的日期 table 列名称