SQL如何在未找到的日期填充零

时间:2016-08-12 20:12:56

标签: sql sql-server

我有以下SQL查询:

SELECT SUM(data.frequency) as total,
data.day as day, 
data.weekday,
CASE data.weekday 
WHEN 1 THEN 'SUN'
WHEN 2 THEN 'MON'
WHEN 3 THEN 'TUE'
WHEN 4 THEN 'WED'
WHEN 5 THEN 'THU'
WHEN 6 THEN 'FRI'
WHEN 7 THEN 'SAT'
END as weekday
FROM (
SELECT COUNT(createdate) as frequency,
DATEPART(day,createdate) as day, 
DATEPART(weekday,createdate) as weekday,
createdate as createddate
FROM requests ma
WHERE createdate BETWEEN 
@startdate
AND
@enddate

GROUP BY datepart(day,createdate),DATEPART(weekday,createdate),createdate

) data
GROUP BY data.day,data.weekday, CASE data.weekday 
WHEN 1 THEN 'SUN'
WHEN 2 THEN 'MON'
WHEN 3 THEN 'TUE'
WHEN 4 THEN 'WED'
WHEN 5 THEN 'THU'
WHEN 6 THEN 'FRI'
WHEN 7 THEN 'SAT'
END
order by day

这将返回如下表格:

enter image description here

  

这是理想的选择,但我可以在缺少一天或多天的情况下获取查询,然后我想用dayweekdayweekdaylabel填充缺失的行并为总列设置值 0

有任何线索吗?

1 个答案:

答案 0 :(得分:0)

DECLARE @startdate DATE = '1/1/2016'
DECLARE @enddate DATE = '2/1/2016'

;WITH cteDates AS (
    SELECT @startdate AS [Date]
    UNION ALL
    SELECT
       DATEADD(day,1,Date) AS [Date]
    FROM
       cteDates c
    WHERE
       c.Date <= @enddate
)

SELECT
    d.[Date]
    ,COUNT(*) as frequency
    ,DAY(d.[Date]) as [day]
    ,DATEPART(weekday,d.[Date]) as [weekday]
    ,LEFT(DATENAME(dw,d.[Date]),3) as weekdaylabel 
FROM
    cteDates d
    LEFT JOIN requests ma
    ON d.[Date] = ma.createdate
GROUP BY
    d.[Date]
ORDER BY
    [day]

使用递归cte构建一个包含所需日期的日期表,然后简单地将您的请求表加入并计数()聚合。

您可以使用几种更简单的方法,通过使用不同的功能获得所需的相同信息。当您使用这些功能,因为它们是在[日期]上构建的,您也不必将它们包含在组中。