SQL Server 2008中的复杂连接

时间:2013-02-20 21:54:47

标签: sql sql-server-2008-r2 left-join

我正在尝试为符合以下身份证的所有申请人打印所有规则(626,1985,2511)。

它打印出626作为第一条规则的申请人,但它不打印那些只有1985年和2511而没有626的申请人。有什么想法吗?

select DISTINCT AD1.AppID,

MAX(CASE WHEN (APDR1.SETTINGID= 626) THEN APDR1.reviewruletext    ELSE ' ' END)AS 'Rule1',
MAX(CASE WHEN (APDR2.SETTINGID= 1985)THEN APDR2.reviewruletext    ELSE ' ' END)AS 'Rule2', 
MAX(CASE WHEN (APDR8.SETTINGID= 2511) THEN APDR8.reviewruletext    ELSE ' ' END)AS 'Rule8' 


from  appdetail  ad1

LEFT OUTER JOIN AppPartyDetailRule   APDR1 on
  apdr1.AppID=ad1.AppID AND 
 apdr1.AppDetailID= ad1.AppDetailID and
 apdr1.AppDetailSavePointID= AD1.AppDetailSavePointID AND
 ad1.AppDetailSavePointID=0 AND
 APDR1.SettingID= 626 



LEFT OUTER JOIN AppPartyDetailRule APDR2on
 ad1.appid= apdr2.appid and 
 ad1.appdetailID= apdr2.appdetailID and 
 ad1.appdetailsavepointid= apdr2.appdetailsavepointid and
 ad1.appdetailsavepointid= 0 AND
 APDR2.SettingID= 1985


LEFT OUTER JOIN AppPartyDetailRule APDR8 on
 ad1.appid= apdr8.appid and 
 ad1.appdetailID= apdr8.appdetailID and 
 ad1.appdetailsavepointid= apdr8.appdetailsavepointid and
 ad1.appdetailsavepointid= 0 AND
 APDR8.SettingID= 2511 


 group by AD1.AppID,....  etc. (more fields)

表结构是:
AppID,AppDetailID,AppDetailsavepointID构成链接到的AD1表中的主键 APDR几次使用上面的PK,每次为settingID提取不同的值。

所需的输出是: AppID审核规则text1,审核规则text2,审核规则文本8

审查规则Text1代表626,2是1985,8是2511,每个代表一定的规则

1 个答案:

答案 0 :(得分:1)

我认为您可以将查询简化为:

select AD1.AppID,
       MAX(CASE WHEN (APDR1.SETTINGID = 626) THEN APDR1.reviewruletext ELSE ''
           END) AS 'Rule1',
       MAX(CASE WHEN (APDR1.SETTINGID = 1985) THEN APDR1.reviewruletext ELSE ''
           END) AS 'Rule2',  
       MAX(CASE WHEN (APDR1.SETTINGID = 2511) THEN APDR1.reviewruletext ELSE ''
           END) AS 'Rule8'
from appdetail ad1 LEFT OUTER JOIN
     AppPartyDetailRule APDR1
     on apdr1.AppID=ad1.AppID AND 
        apdr1.AppDetailID= ad1.AppDetailID and
        apdr1.AppDetailSavePointID= AD1.AppDetailSavePointID AND
        ad1.AppDetailSavePointID=0
group by ad1.appID
where APDR1.SettingID in (626, 1985, 2511)