我的表格有两列sale_date
和amount
:
sale_date amount
-------------------
05/01/2014 400
05/02/2014 350
05/04/2014 430
.
.
如果特定日期没有销售,我希望输出包含amount
的零值。
期望的输出:
sale_date amount
-------------------
05/01/2014 400
05/02/2014 350
05/03/2014 0
05/04/2014 430
.
.
答案 0 :(得分:2)
考虑这是你的表
CREATE TABLE #TEMP(sale_date DATE, AMOUNT NUMERIC(18,2))
INSERT INTO #TEMP
SELECT '05/01/2014', 400
UNION ALL
SELECT '05/02/2014', 350
UNION ALL
SELECT '05/04/2014', 430
我在查询中编写了逻辑
DECLARE @MAXDATE DATE
SELECT @MAXDATE = MAX(sale_date) FROM #TEMP
; WITH CTE as
(
-- Select minimum date
SELECT MIN(sale_date) as DATES
FROM #TEMP
UNION ALL
-- Increments month recursively till maximum date
SELECT DATEADD(MONTH,1,DATES)
FROM CTE C1
WHERE DATES < @MAXDATE
)
SELECT DISTINCT DATES,ISNULL(T1.AMOUNT ,0)AMOUNT
FROM CTE C1
LEFT JOIN #TEMP T1 ON C1.DATES=T1.sale_date