企A p -------------------- P1 P2 P3 P4 企B p val -------------------- ----------- P1 100 P2 20 P4 200 企C pp -------------------- P1 = P4 蟆郁骸 p val ---------- ----------- P1 200 P2 20 P3 0 P4 400讌覓語覲: http://devpia.com/Maeul/Contents/Detail.aspx?BoardID=41&MAEULNO=17&no=2059&ref=2059&page=1
use tempdb go create table A(p varchar(20)) create table B(p varchar(20), val int) create table C(pp varchar(20)) insert A values('P1') insert A values('P2') insert A values('P3') insert A values('P4') insert B values('P1', 100) insert B values('P2', 20) insert B values('P4', 200) insert C values('P1 = P4') select * from A select * from B select * from C */
select convert(varchar(10), A.p) p , isnull(sum(B.val), 0) val from ( select p from A union all select case when T.seq = 1 then left(pp, charindex('=', pp) - 1) else substring(pp, charindex('=', pp) + 1, 8000) end p from ( select replace(pp, ' ', '') pp from C) C cross join (select 1 seq union all select 2) T) A left outer join B on A.p = B.p group by A.p order by A.p
with cte (p) as ( select case when T.seq = 1 then left(pp, charindex('=', pp) - 1) else substring(pp, charindex('=', pp) + 1, 8000) end p from ( select replace(pp, ' ', '') pp from C) C cross join (select 1 seq union all select 2) T ) select convert(varchar(10), A.p) p , isnull(sum(B.val), 0) val from ( select p from A union all select p from cte) A left outer join B on A.p = B.p group by A.p order by A.p