我正在寻找针对以下问题的SQL解决方案:
SQLFiddle作为指导:
我有一个不可空的startdates和可空的enddates列表。基于此列表,我需要在给定的开始和结束日期之间的总间隔时间。
基于SQLFiddle
如果我的数据库中只有情况1,结果应为2天。 如果我的数据库中有情况2和3,结果应该是1天。
我一直在思考这几天......任何帮助都会非常感激!
此致 Kyor
注意:我正在运行SQL 2012(如果需要任何特殊的新功能)
答案 0 :(得分:1)
最好的解决方案是创建“日期”表并从那里开始,否则解决方案将无法维护。对于指定范围内的每个日期,您可以检查“日期范围”表中的范围是否涵盖范围,并获取非日期的计数。
这样的事情:
SELECT COUNT(*)
FROM
Dates d
WHERE
d.Date BETWEEN @start AND @end
AND NOT EXISTS
(SELECT *
FROM dateranges r
WHERE d.date BETWEEN r.startdate and ISNULL(r.enddate, d.date)
)
答案 1 :(得分:0)
CREATE TABLE Dates (
dt DATETIME NOT NULL PRIMARY KEY);
INSERT INTO Dates VALUES('20081204');
INSERT INTO Dates VALUES('20081205');
INSERT INTO Dates VALUES('20090608');
INSERT INTO Dates VALUES('20090609');
-- missing ranges
SELECT DATEADD(DAY, 1, prev) AS start_gap,
DATEADD(DAY, -1, next) AS end_gap,
DATEDIFF(MONTH, DATEADD(DAY, 1, prev),
DATEADD(DAY, -1, next)) AS month_diff
FROM (
SELECT dt AS prev,
(SELECT MIN(dt)
FROM Dates AS B
WHERE B.dt > A.dt) AS next
FROM Dates AS A) AS T
WHERE DATEDIFF(DAY, prev, next) > 1;
-- existing ranges
SELECT MIN(dt) AS start_range,
MAX(dt) AS end_range
FROM (
SELECT dt,
DATEDIFF(DAY, ROW_NUMBER() OVER(ORDER BY dt), dt) AS grp
FROM Dates) AS D
GROUP BY grp;
DROP TABLE Dates;