求一条统计的SQL语句

idealzxh 2006-08-29 02:52:25


部门 金额
01 -123
01 123
02 -123
02 123
02 -123
03 123
03 -123
04 123
04 -123
想用一次查询统计表中每个部门的负数合计,正数合计(用一个存储过程也好),谢谢
...全文
201 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
toto1980 2006-08-29
  • 打赏
  • 举报
回复
select 部门,正总和 = sum(case when 金额 > 0 then 金额 else 0 end),
负总和 = sum(case when 金额 < 0 then 金额 else 0 end)from @t
group by 部门
toto1980 2006-08-29
  • 打赏
  • 举报
回复
declare @t table (部门 varchar(10),金额 int)
insert into @t
select '01',-123
union all select '01',123
union all select '02',-123
union all select '02',123
union all select '02',-123
union all select '03',123
union all select '03',-123
union all select '04',123
union all select '04',-123

select 部门,sum(金额) as 总和 from @t
group by 部门,(case when 金额 > 0 then 1 else 2 end)
wolaile27 2006-08-29
  • 打赏
  • 举报
回复
up
zlp321002 2006-08-29
  • 打赏
  • 举报
回复
SELECT 部门,正合计金额=SUM(CASE WHEN 金额>=0 THEN 金额 END),
负合计金额=SUM(CASE WHEN 金额<0 THEN 金额 END)
FROM 表 A
GROUP BY 部门
WangZWang 2006-08-29
  • 打赏
  • 举报
回复
select 部门,
负数金额=sum(case when 金额<0 then 金额 else 0 end),
正数金额=sum(case when 金额<0 then 0 else 金额 end)
from 表 group by 部门
WangZWang 2006-08-29
  • 打赏
  • 举报
回复
select 部门,
负数金额=sum(case when 金额<0 then 金额 else 0 end),
正数金额=sum(case when 金额<0 then 0 else 金额 end),
from 表 group by 部门
WangZWang 2006-08-29
  • 打赏
  • 举报
回复
select 部门,金额=sum(case when 金额<0 then 金额 else 0 end)
from 表 group by 部门

27,580

社区成员

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

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