我正在尝试对此查询进行自我加入,并继续收到错误invalid object name x
select row_number() over(order by patientid,admissiondate, claimsfromdate,datediff(dd,admissiondate, claimsfromdate)) as rn
,x.patientid, x.admissiondate, x.claimsfromdate, x.rehabwait
from
(
SELECT distinct
patientid
,admissiondate
,claimsfromdate
,DATEDIFF(dd, admissiondate, claimsfromdate) as rehabWait, hcpcs
FROM Claims
WHERE hcpcs in ('g0151', '97001', '97002', '9339') and claimsfromdate > admissiondate
) x inner join x as x2 on x.patientid=x2.patientid
如果不将其保存为视图或将查询重写两次(一次在内部,一次在内部联接中),我不能这样做,可以吗?
答案 0 :(得分:1)
使用CTE:
with x as (
SELECT distinct patientid, admissiondate, claimsfromdate,
DATEDIFF(dd, admissiondate, claimsfromdate) as rehabWait, hcpcs
FROM Claims
WHERE hcpcs in ('g0151', '97001', '97002', '9339') and
claimsfromdate > admissiondate
)
select row_number() over (order by patientid, admissiondate,
claimsfromdate,
datediff(dd,admissiondate, claimsfromdate)
) as rn,
x.patientid, x.admissiondate, x.claimsfromdate, x.rehabwait
from x inner join
x as x2
on x.patientid=x2.patientid
解决了原来的问题后,我看不到你在使用x2了。它不会出现在“SELECT”语句中。您所做的就是为特定患者创建所有索赔的交叉产品。也许这是合理的。我希望group by成为这样一个查询的一部分。
答案 1 :(得分:0)
你不能以这种方式JOIN
表。您可能需要创建两次引用的视图,或者您可以执行以下操作:
SELECT row_number() over(order by patientid, admissiondate, claimsfromdate, rehabWait) as rn
, x.patientid
, x.admissiondate
, x.claimsfromdate
, x.rehabwait
FROM
(
SELECT distinct
c1.patientid
, c1.admissiondate
, c1.claimsfromdate
, DATEDIFF(dd, c1.admissiondate, c1.claimsfromdate) as rehabWait
, c1.hcpcs
FROM Claims c1
INNER JOIN Claims c2
ON c1.patientid = c2.patientid
WHERE c1.hcpcs in ('g0151', '97001', '97002', '9339') and c1.claimsfromdate > c1.admissiondate
) x