SQL中用Join 进行SUM时令我困惑的问题

sunmoonn 2006-03-09 06:18:25
表A 表B 表C
ID Name Name Count Name Count
1 笔 笔 2 笔 -1
笔 -1


当我用下面的SQL进行SUM时
select A.Name, SUM(B.Count)as B_Count,SUM(C.Count) as C_Count
from A left outer join B on A.Name=B.Name
left outer join C on A.Name=C.Name
Group by A.Name

/*-----结果-------*/
Name B_Count C_Count
笔 4 -2

各位大虾
我这条SQL怎么改才正确能啊
正确应为
Name B_Count C_Count
笔 2 -2
...全文
198 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
wgsasd311 2006-03-09
  • 打赏
  • 举报
回复
汗,
楼主,我的方法不对,没有仔细看清.可可方法很好.
sunmoonn 2006-03-09
  • 打赏
  • 举报
回复
lsqkeke(可可) 的非常正确
wgsasd311(自强不息) 应该能行
WangZWang(阿来) 改得我头晕(可能我比较差)

总之很感谢你们几位
dashi111 2006-03-09
  • 打赏
  • 举报
回复
select A.name,
'b_count'=(select sum(B.count1) from B where B.name=A.name),
'c_count'=(select sum(C.count1) from C where C.name=A.name)
from A group by A.name
lsqkeke 2006-03-09
  • 打赏
  • 举报
回复
select [Name],
B_Count=isnull((select sum([count]) from B where [name]=A.[name]),0),
C_Count=isnull((select sum([count]) from C where [name]=A.[name]),0)
from A
lsqkeke 2006-03-09
  • 打赏
  • 举报
回复
declare @t1 table(id int,[name] varchar(5))
insert @t1
select 1,'笔'

declare @t2 table([name] varchar(5),[count] int)
insert @t2
select '笔',2

declare @t3 table([name] varchar(5),[count] int)
insert @t3
select '笔',-1 union all
select '笔',-1

select A.[Name],
B_Count=(select sum([count]) from @t2 where [name]=a.[name]),
C_Count=(select sum([count]) from @t3 where [name]=a.[name])
from @t1 a
group by [name]

笔 2 -2
wgsasd311 2006-03-09
  • 打赏
  • 举报
回复
--不好意思,上面看错了,试试下面
select A.Name, SUM(B.Count)/COUNT(distinct c.count) as B_Count,SUM(C.Count) as C_Count
from A left outer join B on A.Name=B.Name
left outer join C on A.Name=C.Name
Group by A.Name
wgsasd311 2006-03-09
  • 打赏
  • 举报
回复
select A.Name, COUNT(B.Count)as B_Count,SUM(C.Count) as C_Count
from A left outer join B on A.Name=B.Name
left outer join C on A.Name=C.Name
Group by A.Name
WangZWang 2006-03-09
  • 打赏
  • 举报
回复
select A.Name, SUM(B.Count)as B_Count,SUM(x.Count) as C_Count
from A left join B on A.Name=B.Name
left join (Select name,count=sum(count) from C
group by name) as x on A.Name=x.Name
Group by A.Name

34,587

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧