2017-02-23 72 views
0

我需要編寫SQL查詢的幫助。我的桌子是:MS-SQL 2008 isues與多表查詢

提供: contribution_id |數額| person_id | currency_type

Person_id |名字|姓氏

相關 related_id | person_id | related_personID

貨幣類型 CurrencyTypeID |貨幣名稱

還有其他表和字段,但這些是我需要的。

這是我遇到的問題..

當一個人貢獻了第一個和最後的名字很容易,但是當一個經紀公司貢獻,我需要包括真實的人的名字和姓氏(不經紀賬戶)。 經紀與該人在同一張桌子上。

到目前爲止,我有如果contribution.currencyType = '12492'然後我需要從相關的表中找到信息,以找到真正的person_id。 當我運行下面的代碼時,我得到的是所有數據,除非currencytype = 12492然後我爲姓和名得到空。 這是到目前爲止我的代碼:

`

declare @fund int = 165 
declare @payment_luid int = 58 
DECLARE @report_information TABLE(
           ContributionID varchar(20), 
           ContributionDate date, 
           firstname varchar(50), 
           lastname varchar(50), 
           memberID varchar(20), 
           Pledge money, 
           cash money, 
           non_cash money, 
           fund_name VARCHAR(50)) 
INSERT INTO @report_information 
SELECT c.contribution_id, 
    c.contribution_date, 
    case when c.currency_type = '12492' then t3.first_name else  t1.first_name end, 
    case when c.currency_type = '12492' then t3.last_name else t1.last_name end, 
    case when c.currency_type = '12492' THEN t3.person_id else c.person_id end as MemberID, 
    case when c.currency_type = '12492' then (select amount From ctrb_pledge where ctrb_pledge.person_id = t3.person_id and fund_id = @fund) else (select amount from ctrb_pledge where ctrb_pledge.person_id = c.person_id and fund_id [email protected]) END, 
    CASE WHEN C.currency_type_luid NOT IN (SELECT lookup_id FROM core_lookup WHERE [email protected]_luid AND lookup_qualifier2 ='1') THEN CCF.amount ELSE 0 END, 
    CASE WHEN CCF.non_cash = 1 OR C.currency_type IN (SELECT lookup_id FROM core_lookup WHERE [email protected]_luid AND lookup_qualifier2 ='1') THEN CCF.amount ELSE 0 END, 
    f.fund_name 
    FROM contribution as c 
left join core_person as t1 
on t1.person_id = c.person_id 
left join relationship as t2 
on t2.person_id = c.person_id 
left join person as t3 
on related_person_id = c.person_id 
JOIN ctrb_contribution_fund CCF ON CCF.contribution_id=C.contribution_id 
JOIN ctrb_fund F ON F.fund_id = CCF.fund_id 
where f.fund_id = @fund 
order by contribution_id 
SELECT lastname 
    ,firstname 
    ,memberID 
    ,coalesce(SUM(pledge),0) as Pledge 
    ,SUM(cash) AS cash_gifts 
    ,SUM(non_cash) AS non_cash_gifts 
    ,SUM(cash + non_cash) as TotalGiving 
    ,coalesce(SUM(pledge)-(SUM(cash)+SUM(non_cash)),0) as Balance 
    ,fund_name 
FROM @report_information 
GROUP BY memberid, lastname, firstname, fund_name 
ORDER BY lastname asc 

`

回答

0

我想這個問題了。通過將連接語句更改爲FULL JOIN OUTER,我的丟失記錄出現了。

join core_person as cp 
on cp.person_id = c.person_id 
full outer join core_relationship as rel 
on rel.person_id = c.person_id 
full outer join core_person as newCp 
on rel.related_person_id = newcp.person_id 

我確實將我的表更改爲我能記得的東西。 t1 = cp,t2 = rel,t3 = newcp。