多表合并的问题 请大家帮帮忙
有表四张
表A 如下
djbh spid shl pihao
a001 A 20 123
a001 B 5 223
a001 C 10 456
表 B 如下
djbh spid shl pihao
a002 A 10 123
a002 A 10 789
a002 B 20 224
a002 B 10 223
a002 C 30 456
表 C 如下
djbh spid shl pihao
a003 B 10 223
a003 B 5 662
a003 C 10 456
表 S 如下
spid spmch
A 茅台
B 五粮液
C 古井贡
想实现如下结果
spid spmch pihao hjsl djbh1 shl1 djbh2 shl2 djbh3 shl3
A 茅台 123 80 a001 20 a002 10 null null
A 茅台 789 10 null null a002 10 null null
B 五粮液 223 25 a001 5 a002 10 a003 10
B 五粮液 224 20 null null a002 20 null null
C 古井贡 456 50 a001 10 a002 30 a003 10
小弟初学请大家帮帮忙 谢谢了
------解决方案--------------------SELECT A.SPID AS SPID,A.SPMCH AS SPMCH,B.HJSL AS HJSL,B.PIHAO AS PIHAO,C.DJBH AS DJBH1,C.SHL AS SHL1,D.DJBH AS DJBH2,D.SHL AS SHL2,E.DJBH AS DJBH3,E.SHL AS SHL3 FROM S A LEFT JOIN (SELECT SUM(SHL) HJSL,SPID,PIHAO FROM(SELECT SHL,SPID,PIHAO FROM A UNION ALL SELECT SHL,SPID,PIHAO FROM B UNION ALL SELECT SHL,SPID,PIHAO FROM C)GROUP BY SPID,PIHAO)B LEFT JOIN A C ON A.SPID=C.SPID LEFT JOIN B D ON A.SPID=D.SPID LEFT JOIN C E ON A.SPID=E.SPID ORDER BY A.SPID,A.SPMCH,B.PIHAO