求汇总Sql 在线等

zhangyang555 2006-05-09 10:52:44
表结构如下:

Type Parent ChildType Number
2 6 2 500
2 6 1 600
1 3 1 300
1 3 1 500
1 3 2 100
3 1 1 100
3 1 2 100
3 1 2 900

ChildType 取值为1和2

需得以下汇总结果(根据ChildType的值对Number求和):
Type Parent SumChildType1 SumChildType2
1 3 800 100
2 6 600 500
3 1 100 1000
...全文
108 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhangyang555 2006-05-09
  • 打赏
  • 举报
回复
兄弟可以留个联系方式不,QQ/MSN都可以,以后有问题我就直接把帖子的地址发给你
子陌红尘 2006-05-09
  • 打赏
  • 举报
回复
select
Type,
Parent,
SumChildType1=sum(case ChildType when 1 then Number else 0 end),
SumChildType2=sum(case ChildType when 2 then Number else 0 end)
from

group by
Type,Parent
xeqtr1982 2006-05-09
  • 打赏
  • 举报
回复
create table tb(Type int,Parent int,ChildType int,Number int)
insert into tb select 2,6,2,500
union all select 2,6,1,600
union all select 1,3,1,300
union all select 1,3,1,500
union all select 1,3,2,100
union all select 3,1,1,100
union all select 3,1,2,100
union all select 3,1,2,900

declare @sql varchar(8000)
set @sql='select Type,Parent'
select @sql=@sql+',[SumChildType'+cast(ChildType as varchar)+']=sum(case ChildType when '+cast(ChildType as varchar)+' then Number else 0 end)' from tb group by ChildType
exec(@sql+' from tb group by Type,Parent order by Type')

drop table tb
WangZWang 2006-05-09
  • 打赏
  • 举报
回复
select Type,Parent,
sumChildType1=sum(case when ChildType=1 then Number else 0 end),
sumChildType2=sum(case when ChildType=2 then Number else 0 end)
from table
group by Type,Parent
order by type

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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