当前位置: 代码迷 >> Sql Server >> 一个一对多关系的分组查询的一点有关问题?等
  详细解决方案

一个一对多关系的分组查询的一点有关问题?等

热度:354   发布时间:2016-04-27 16:24:25.0
一个一对多关系的分组查询的一点问题?等
create   table   a(
code   int,
cname   varchar(10)
)
create   table   b(
zID   int   identity,
code   int,
days   float
)

insert   into   a   values(1, 'aaa ')
insert   into   a   values(2, 'bbb ')
insert   into   a   values(3, 'ccc ')

insert   into   b   values(1,0.5)
insert   into   b   values(2,0.5)
insert   into   b   values(3,4)
insert   into   b   values(1,25)
insert   into   b   values(2,14)
insert   into   b   values(3,14)
insert   into   b   values(1,7)
insert   into   b   values(2,6)
insert   into   b   values(3,4)
insert   into   b   values(3,8)

表a和表b是一对多的关系,
现在想查询得到的结果是
a.code     b.days
1               32.5
2               20.5
3               30
我写的语句怎么总是通不过撒

select   a.*,b.[count]   from   a,(
select   b.zID   as   JID,count(*)   as   [count]   from   a   left   join   b   on   a.code=b.code
group   by   b.code
)b


------解决方案--------------------

select a.code ,sum(b.days) as [days]
from a join b on a.code =b.code
group by a.code
------解决方案--------------------
select a.code,m.days from a left join
(
select code,days=sum(days) from b group by code
)m on a.code=m.code
  相关解决方案