Joe
Joe

Reputation: 173

complex joins in SQL Server 2008

I am trying to print all rules for all applicants that meet the following ID (626, 1985, 2511).

It prints the applicants that have 626 as a first rule, but it does not print the ones that have only 1985 and 2511 and no 626). Any idea?

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)

table structure is:
AppID, AppDetailID, AppDetailsavepointID make up the primary key in AD1 table which is linked to APDR a few times using the PK above and each time it extract a different value for settingID.

Desired Output is: AppID review rule text1, review rule text2, review rule text 8

review Rule Text1 represent 626, 2 is 1985 and 8 is 2511 and each represent a certain rule

Upvotes: 0

Views: 482

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269923

I think you can simplify your query to:

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)

Upvotes: 1

Related Questions