这是我在sql server 2008中的SP:
SELECT
CONVERT(NVARCHAR(30), YMD, 101) AS [DATE],
SUM(ISNULL(Jobs, 0)) AS [Jobs],
SUM(ISNULL(SELL_VALUE, 0)) AS [COST]
FROM S
WHERE [YMD] BETWEEN @DateFrom AND @DateTo
GROUP BY YMD
ORDER BY YMD DESC
这里我的@DateFrom和@DateTo是2014年7月23日到2014年7月29日。
结果来了:
DATE Jobs Cost 7/29/2014 1 $0.00 7/28/2014 4 $0.00 7/27/2014 3 $0.06 7/25/2014 4 $0.00 7/23/2014 1 $0.00
现在我想要的是:
DATE Jobs Cost 7/29/2014 1 $0.00 7/28/2014 4 $0.00 7/27/2014 3 $0.05 7/26/2014 0 $0.00 7/25/2014 4 $0.00 7/24/2014 0 $0.00 7/23/2014 1 $0.00
即。它应该显示缺少日期的行,为除日期1之外的所有列输入“0”。
答案 0 :(得分:1)
我同意@bluefeet方法
为了创建动态的from-to日历,你可以使用像这样的递归cte:
DECLARE @DateFrom AS DATE
DECLARE @DateTo as DATE
SET @DateFrom='7/23/2014'
SET @DateTo ='7/29/2014'
;WITH r AS
(SELECT @DateFrom AS calendardate
UNION ALL
SELECT DATEADD(d,1,calendardate) FROM r
WHERE DATEADD(d,1,calendardate)<=@DateTo
)
SELECT * FROM r
答案 1 :(得分:0)
DECLARE @DateFrom DATE
DECLARE @DateTo DATE
SET @DateFrom = '7/23/2014'
SET @DateTo = '7/29/2014'
--BEGIN Add this
DECLARE @X DATE
DECLARE @D TABLE (EachDay Date)
SET @X = @DateFrom
WHILE @X <= @DateTo BEGIN
INSERT INTO @D VALUES (@X)
SET @X = DATEADD(day, 1, @X)
END
SELECT * FROM @D
--END Add this
SELECT
CONVERT(NVARCHAR(30), YMD, 101) AS [DATE],
SUM(ISNULL(Jobs, 0)) AS [Jobs],
SUM(ISNULL(SELL_VALUE, 0)) AS [COST]
FROM S
--ADD This - just the one following line
RIGHT OUTER JOIN @D as D ON D.EachDay = S.YMD
WHERE [YMD] BETWEEN @DateFrom AND @DateTo
GROUP BY YMD
ORDER BY YMD DESC