sql的sum问题,高手来

来源:百度知道 编辑:UC知道 时间:2024/05/22 05:22:41
假设表m,有a,b两个字段,现在要在1条记录里显示 b=1时的sum(a)和b=2时的sum(a),注意是一条记录显示,不是group by。
select sum(a)[b=1时] ,sum(a)[b=2时] from m

declare @sum1 int
declare @sum2 int
select @sum1=sum(a) from m where b=1
select @sum2=sum(a) from m where b=2
select @sum1,@sum2

如果是要求一句的话:
select (select sum(a) from m where b=1),(select sum(a) from m where b=2)

可以用union
select sum(a),b from m where b=1 group by b
union
select sum(a),b from m where b=2 group by b

写的太不详细了。你想一条纪录怎么显示,你先举个例子

还不是太清楚,我想知道的是你的结果想怎么显示。同一个表m内a 和b有什么逻辑关系?
不过先试着写个
select b,sum(a) from m where b in(select b from m)