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

How to Show missing Date based on a given date range?

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

1
2
3
4
5
6
7
8
9
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

我的当前输出是:

1
2
3
Business DATE   Refund Amount
  20160202            14
  20160203            19

应该是:

1
2
3
4
Business DATE   Refund Amount
  20160201             0
  20160202            14
  20160203            19

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


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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]