我有这个查询。它创建了一个日历,用于在医疗索赔中与DOS进行比较,以计算不同的天数。
当我运行它时,我似乎放下了几行,这些行不会出现在我的结果中。
任何人都可以看到为什么这些行不会在此查询中计算?
ICN From Date of Service To Date of Service Detail Status Code 12345 20121102 12:00:00 20121103 12:00:00 P 12345 20121102 12:00:00 20121103 12:00:00 P 12345 20121102 12:00:00 20121103 12:00:00 P 12345 20121102 12:00:00 20121103 12:00:00 D 12345 20121102 12:00:00 20121103 12:00:00 D 12345 20121102 12:00:00 20121103 12:00:00 D 12345 20121102 12:00:00 20121103 12:00:00 D 12345 20121102 12:00:00 20121103 12:00:00 D
CREATE TABLE #Calendar1(Dt DATETIME NOT NULL PRIMARY KEY);
;WITH cte AS
(
SELECT CAST('20120101' AS DATETIME) AS c
UNION ALL
SELECT DATEADD(dd,1,c) FROM cte
WHERE c < '20131231'
)
INSERT INTO #Calendar1 SELECT c FROM cte OPTION (MAXRECURSION 1);
SELECT
ICN,
COUNT(DISTINCT Dt) AS Days
FROM
AllOPBYDOS s
INNER JOIN #Calendar1 c ON
s.[from Date of service] >= c.Dt AND s.[to Date of service] < c.Dt+1
--Where [Detail Status Code] = 'p'
GROUP BY
ICN;
答案 0 :(得分:0)
当我在SQL Server 2008上运行日历查询时,它只生成一行。我想你想要:
INSERT INTO #Calendar1 SELECT c FROM cte OPTION (MAXRECURSION 0);
对于已删除的行,您确定它们的日历范围内有日期吗?你应该做一个左外连接并检查极端情况:
SELECT ICN, COUNT(DISTINCT Dt) AS Days,
sum(case when [from Date of service] not between const.mindt and const.maxdt or
[to Date of service] not between const.mindt and const.maxdt
then 1
else 0
end) as OutOfRangeRecords
FROM AllOPBYDOS s left outer JOIN
#Calendar1 c
ON s.[from Date of service] >= c.Dt AND s.[to Date of service] < c.Dt+1 cross join
(select MAX(dt) as maxdt, MIN(dt) as mindt from #Calendar1) const
GROUP BY ICN;