面临的挑战是在连续日期找到差距。
我试过这样的事情
WITH t AS (
SELECT a a, d d, c, ROW_NUMBER() OVER(ORDER BY a) i
FROM p
)
SELECT MIN(a),MAX(d), c
FROM t
GROUP BY DATEDIFF(day,i,d), c
我正在使用sql数据库。 任何人都可以从这一步帮助?? 提前致谢
答案 0 :(得分:2)
您需要识别范围组 - 但您需要识别分组。这是一种直接在SQL Server 2012+中工作的方法(可以修改为在早期版本中工作):
所以:
select patientid, min(admissiondate), max(dischargedate), sum(cost)
from (select p.*,
sum(RangeFlag) over (partition by patientid order by admissiondate) as grp
from (select p.*,
(case when admissiondate = dateadd(day, 1,
lag(dischargedate) over (partition by patientid order by admissiondate))
then 0
else 1
end) as RangeFlag
from patients p
) p
) p
group by patientid, grp;