按CTE Sql Server 2008计算的总减法总数我需要基于它们的行号的两个值之间的差异。像 按照ID#
的CTE返回的数据我想要做的是有2行中rehabWait列(92-32)读60
和排三60以及(152-92`)等等,直到有一个在patientid改变。因此,对于第11行,我想让rehabwait成为110(114-4)。查询我会跑起来,但是它返回所有NULLS
with x as
(
SELECT row_number() over (order by patientid, admissiondate, claimsfromdate, datediff(dd,admissiondate, claimsfromdate))as rn,
patientid, admissiondate, claimsfromdate,
DATEDIFF(dd, admissiondate, claimsfromdate) as rehabWait, hcpcs
FROM Claims
WHERE hcpcs in ('g0151', '97001', '97002', '9339') and
claimsfromdate > admissiondate
group by patientid, admissiondate, claimsfromdate, hcpcs
--adding this group by clause will keep rehabWait from showing up
--however many times they patient has the HCPCS code for rehab
)
select x.patientid
,x.admissiondate
,x.claimsfromdate
,(select x2.rehabWait-x.rehabwait from x where x.patientid=x2.patientid
and x.rn > x2.rn and x.admissiondate=x2.admissiondate and x.claimsfromdate=x2.claimsfromdate
)
from x inner join
x as x2 on x.patientid=x2.patientid and x.admissiondate=x2.admissiondate and x.claimsfromdate = x2.claimsfromdate
请参阅我的编辑,我给你的第一个查询并不完全符合你的要求。 – Aushin 2012-08-03 18:01:12