2017-02-23 75 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。