当日期序列中没有可用数据时显示零值

时间:2015-02-02 08:59:20

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

我的表格有两列sale_dateamount

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
.
.

1 个答案:

答案 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