我正在编写一个函数来计算每个月收到的邮件总数。但是使用Group By DATEADD函数仅获取非o计数值。 我需要得到0计数内的所有值。
SELECT(MAX(ReceivedMonthofYear)+''+ MAX(ReceivedYear))AS MonthStartDate,COUNT(ReceivedDateTime)AS MonthlyTotal FROM tblMessageReceived GROUP BY DATEADD(月,DATEDIFF(月,0,ReceivedDateTime),0)
实际上我想得到给定范围内所有值的输出,同时还有0个计数值和几个月。
谢谢!
答案 0 :(得分:1)
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替换为日期表列名称