I’m trying to do a self join on this query and keep getting the error 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
I can’t do this without saving it as a view or rewriting the query out twice (once in the from, once in the inner join), can I?
Use a CTE:
Having fixed your original problem, I do not see what you are using x2 for. It doesn’t appear in the “SELECT” statement. All you are doing is creating a cross product of all claims for a given patient. Perhaps this is reasonable. I would expect a group by to be part of such a query.