当前位置: 代码迷 >> Sql Server >> 一个多表关联查询
  详细解决方案

一个多表关联查询

热度:42   发布时间:2016-04-24 10:46:01.0
求助一个多表关联查询
本帖最后由 freescy2002 于 2014-05-12 23:10:28 编辑
突然之间脑子不好使了,写不出来了
三个表分别如下
表a
class
1
2
3
表b
class_id  sx    b_u
1             1     1
1             2     1
2             4     2
2             7     2
表c
user   ud 
小明   1
小白   2
几个表关系说一下,表a中的class 跟表b中的 class_id  关联  sx字段就当是数量
表b中的 b_u跟表c的ud关联,表a作为查询的主表
现在要得出以下的结果,
class ud  user  sum(sx)
1      1   小明    3
2      2    小白  11
3
------解决方案--------------------

with a (class) as
 (select 1 union all select 2 union all select 3),
b(class_id, sx,  b_u) as
(select 1,             1,     1 union all select 1, 2 ,1 union all select 2,4,2 union all select 2,7 ,2),
c([user]  ,ud) as 
(select '小明',   1 union all select '小白',   2)


select class,ud,[USER],SUM(sx) from a left join B on a.class=b.class_id
left join c on b.b_u=c.ud group by class,ud,[user]
------解决方案--------------------

select a.class,c.ud,c.user,SUM(b.sx)
from 表a a
left jion 表b b
on a.class=b.class_id
inner join 表c c
on b.b_u=c.ud
group by a.class,c.ud,c.user
  相关解决方案