我有以下格式的数据:
Date Value
08/28 100
09/01 1
09/01 5
09/10 2
我希望我的输出为:
Date Value
08/28 100
08/29 100
08/30 100
08/31 100
09/01 106
09/02 106
.
.
.
09/10 108
我刚开始使用SQL,所以任何帮助都会受到赞赏。我现在所拥有的是下面的内容,但这与我所寻求的并不相近:
SELECT Date, COUNT(DISTINCT(Service)) AS Value
FROM [Directory]
WHERE Date <= @myDate
GROUP BY Date ORDER BY Date
答案 0 :(得分:1)
首先,您可以使用子查询来获取聚合值
SELECT Date, (SELECT SUM(Value) FROM Directory d WHERE d.Date <= Directory.Date)
FROM [Directory]
WHERE Date <= @myDate
ORDER BY Date
这会给你一些看起来像这样的东西:
Date Value
08/28 100
09/01 101
09/01 106
09/10 108
然后你可以添加一个Date表作为sgeddes建议。本文解释得非常好:http://michaelmorley.name/how-to/create-date-dimension-table-in-sql-server
然后您可以像这样修改您的查询
SELECT DateTable.Date, (SELECT SUM(Value) FROM Directory d WHERE d.Date <= Directory.Date)
FROM [Directory] LEFT OUTER JOIN DateTable on Directory.Date = DateTable.Date
WHERE DateTable.Date <= @myDate
ORDER BY DateTable.Date
获取您正在寻找的数据格式。
答案 1 :(得分:0)
基于sgeddes建议:
选择a.Date,COUNT(DISTINCT(d.Service))AS值
FROM [Directory] d
LEFT OUTER JOIN [Date Table] a on d.Date = a.Date
WHERE Date <= @myDate
GROUP BY Date
ORDER BY Date
答案 2 :(得分:0)
在sqlserver中使用以下脚本:
BEGIN
--If exist then drop temp tables
DROP TABLE #YOURTABLE;
DROP TABLE #TEST1;
DECLARE @MINDATE DATETIME;
DECLARE @MAXDATE DATETIME;
CREATE TABLE #YOURTABLE(
CDATE DATE,
VALUE INT
);
INSERT INTO #YOURTABLE VALUES ('08/28/2014',100),('09/01/2014',1),('09/01/2014',5),('09/10/2014',100);
--select start date and end date from your table
SELECT @MINDATE=MIN(CDATE),@MAXDATE=MAX(CDATE) FROM #YOURTABLE;
CREATE TABLE #TEST1(
CDATE DATE,
VALUE INT
);
;WITH CALENDAR
AS (
SELECT @MINDATE CDATE
UNION ALL
SELECT CDATE + 1
FROM CALENDAR
WHERE CDATE + 1 <= @MAXDATE
)
-- insert all dates with 0 value in temp table
INSERT INTO #TEST1 SELECT CDATE,0 FROM CALENDAR;
--delete dates which are already there in your table
DELETE FROM #TEST1 WHERE CDATE IN (SELECT CDATE FROM #YOURTABLE)
-- insert all dates with values from your table to temporary table which holds dates which are not in your table
INSERT INTO #TEST1 SELECT * FROM #YOURTABLE;
SELECT T1.CDATE,(SELECT SUM(VALUE) FROM #TEST1 T2 WHERE T2.CDATE<=T1.CDATE) FROM #TEST1 T1
END