2012-06-14 140 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