如何使用DATEADD对所需结果进行分组

时间:2016-04-06 09:04:55

标签: sql-server-ce

我正在编写一个函数来计算每个月收到的邮件总数。但是使用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)

这导致查询 Out put of the query

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

谢谢!

1 个答案:

答案 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替换为日期表列名称