简体   繁体   中英

Multiple joins subquery SQL Server 2008

在此输入图像描述

On the left you'll see my design for one table, on the right you'll see the results from the subquery in the SQL below. I'm trying to join the subquery on the three fields patientID,claimsFromDate,claimsThroughDate on tblClaims, and have the outer query associate the correct tblClaims.ID with the three part join.

The errors I'm getting:

line 3, incorrect syntax near the keyword select and incorrect syntax near the ), line 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

EDIT: The inner query is to reconcile a multi column field. It returns 1.5 million rows. the fixed query I ran returned 3.5 million which was

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

Try this:

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

Did you try using 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM