如何根据给定的日期范围显示缺失日期?

时间:2016-03-22 20:36:21

标签: sql sql-server sql-server-2008 sql-server-2012

我有下面的查询工作正常,它显示该特定位置的所有值退款金额多少。但是,如果我想显示月度报告,我需要显示那些日子在我的表1中没有退款,并显示相同的零值:

SELECT businessDate AS 'Business Date'
    ,Sum(convert(DECIMAL, ISNULL(T1.Amount, 0)) * 1) AS 'Refund Amount'
FROM table1 T1
WHERE (
        (T1.id = '1')
        AND (T1.businessDate BETWEEN '20160201' AND '20160229')
        AND (T1.Amount IS NOT NULL)
        )
GROUP BY T1.businessDate

我的当前输出是:

Business Date   Refund Amount
  20160202            14
  20160203            19

应该是:

Business Date   Refund Amount
  20160201             0
  20160202            14
  20160203            19

那么如何修复我的查询以满足上述要求?

1 个答案:

答案 0 :(得分:1)

我会使用递归CTE,如下所示:

WITH cte
AS
    (
        SELECT CAST('2016-02-01' AS date) [Date]
        UNION ALL
        SELECT DATEADD(DAY, 1, [Date])
        FROM cte
        WHERE DATEADD(DAY, 1, [Date]) <= '2016-02-29'
    )

SELECT
    cte.[Date] [Business Date]
    , SUM(CONVERT(decimal, ISNULL(T1.Amount, 0)) * 1) [Refund Amount]
FROM
    cte
    LEFT JOIN (SELECT * FROM table1 WHERE id = 1) T1 ON cte.[Date] = T1.businessDate
GROUP BY cte.[Date]