一个求和的sql语句--sum

表描述:

表名:Sum_Test

Id       Name       Count       Type

1          A               12           1
2          B               12           1
3          C              12            1
4          D              12            1
5          B              12            2
6          B              12            1
7          A              12            2
8          A              12            1
9          C              12            1
10        B              12             1

结果: Type 1 : 84
      Type 2 : 36

求type  为1和2的Count的总和,如果Name即有Type为1也有Type为2的,则该Count算到Type为2的里面,如: A

Type即有1也有2则A的求和时将A的Count值全部算作为Type=2里面

方法一:

现将Type为2的Name的Type值都改为2

UPDATE  Sum_Test  SET  Type=2 WHERE Name IN (SELECT Name FROM Sum_Test SHERE Type=2)

然后再求和

SELECT SUM(Count) FROM Sum_Test GROUP BY Type



方法二:

select sum([count]) from
(
select [count],[Type]='2' from sum_test where [name] in (select [name] from sum_test where type=2)
UNION ALL
select [count],[Type]='1' from sum_test where [name] not in (select [name] from sum_test where type=2)
) t
group by [type]


这两种方法虽然可以得到想要的结果,但是有很大的弊端

 

方法三:

select (select sum([count]) from sum_test) - (select sum(t.counts) from
(select []name, sum([count]) counts from sum_test
where [name] in(select [name] from sum_test where [type] = 2)
group by [name]) t) type1, (select sum(t.counts) from
(select [name], sum([count]) counts from sum_test
where [name] in(select [name] from sum_test where [type] = 2)
group by [name]) t) type2

 

写成一个过程的话我想执行效率会更好!

 

 

代码:

declare @SubTotal int,
        @Total int

set @SubTotal = (select sum(t.counts) from
(select [name], sum([count]) counts from sum_test
where [name] in(select [name] from sum_test where [type] = 2)
group by [name]) t)

set @Total = (select sum([count]) from sum_test)

select @Total - @SubTotal type1, @SubTotal type2

转载于:https://www.cnblogs.com/zhangxj65060130/archive/2008/07/23/1249409.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值