多个连接子查询SQL Server 2008

时间:2012-06-14 15:18:44

标签: sql sql-server-2008 tsql

enter image description here

在左侧,您将看到我的一个表的设计,在右侧,您将在下面的SQL中看到子查询的结果。我正在尝试在tblClaims上的三个字段patientID,claimsFromDate,claimsThroughDate上加入子查询,并让外部查询将正确的tblClaims.ID与三部分连接相关联。

我得到的错误:

  

第3行,关键字select 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万行。 我运行的固定查询返回了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

2 个答案:

答案 0 :(得分:2)

试试这个:

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

答案 1 :(得分: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