2012-08-03 78 views
0

我試圖做一個自我加入此查詢上,並不斷收到錯誤invalid object name x自連接的查詢無效的對象名稱MSSQL 2008

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 

我不能沒有將其保存爲一個視圖做到這一點或重寫查詢兩次(一次在內部,一次在內部連接),我可以嗎?

回答

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」語句中。你所做的只是創建一個給定患者的所有索賠的交叉產品。也許這是合理的。我期望一個羣組成爲這樣的查詢的一部分。

+0

這是兩部分問題的第一部分。我的全部意圖是在patientID和x2.rn> x.rn上加入x2,以減少運算次數。 http://imgur.com/yCN5U其中行號將讀取60(62-32)和第3行60(152-92)。 – wootscootinboogie 2012-08-03 16:10:29

+0

這並沒有在sql server 2008中執行 – wootscootinboogie 2012-08-03 16:14:11

+0

我會等待這個問題;)從SQL Server 2012或Oracle開始,運行總計要容易得多。 – 2012-08-03 16:15:16

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 
相關問題