2012-06-14 195 views
0

enter image description here多加入子查詢的SQL Server 2008

在左邊,你會看到我的設計爲一個表,在右邊你會看到下面的SQL從子查詢的結果。我試圖在tblClaims上的三個字段patientID,claimsFromDate,claimsThroughDate上加入子查詢,並且讓外部查詢將正確的tblClaims.ID與三部分連接相關聯。

我得到的錯誤:

3線,關鍵詞附近的語法不正確選擇靠近and不正確 語法),第12行

select tblClaims.id, t.primaryCode 
from t 
(
select patientid, claimsfromdate, claimsthroughDate, primarycode from myTable 
union 
select patientid, claimsfromDate, claimsthroughDate, secondaryCode from myTable 
union 
select patientID, claimsfromdate, claimsthroughDate, tertiarycode from myTable 

) as t 
inner join t on tblclaims.patientid=t.patientid 
and tblclaims.claimsfromdate=t.claimsfromdate 
and tblclaims.cllaimsthroughdate=t.claimsfromdate 

編輯:內層查詢是協調一個多列字段。它返回150萬行。 這是

select tblClaims.id, t.primarycode from ( select patientid, claimsfromdate, claimsthroughDate, primarycode from myTable ) as t inner join tblclaims on tblclaims.patientid=t.patientid and tblclaims.claimsfromdate=t.claimsfromdate and tblclaims.cllaimsthroughdate=t.claimsfromdate

+0

難怪你沒有看到它 - 之後有t,只是刪除它。 –

回答

2

固定查詢我跑回來350萬試試這個:

select tblClaims.id, t.primarycode 
from 
(
select patientid, claimsfromdate, claimsthroughDate, primarycode from myTable 
) as t 
inner join tblclaims on tblclaims.patientid=t.patientid 
and tblclaims.claimsfromdate=t.claimsfromdate 
and tblclaims.cllaimsthroughdate=t.claimsfromdate 
+0

這會運行,但它會返回大約三倍太多的行,我不認爲它會有所作爲,但是我將編輯查詢以包含整個查詢(我想省去雜亂)。 – wootscootinboogie

0

你嘗試使用Distinct

select DISTINCT tblClaims.id, t.primarycode 
from 
(
    select patientid, claimsfromdate, claimsthroughDate, primarycode from myTable 
) as t 
inner join tblclaims on tblclaims.patientid=t.patientid 
and tblclaims.claimsfromdate=t.claimsfromdate 
and tblclaims.cllaimsthroughdate=t.claimsfromdate