表描述:
表名: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)
) tgroup 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
sql 縱向求和 SQL 多表查詢
實際工作中,絕大部分查詢並非乙個表可以解決,我們需要合併,連線 所有查詢都其實都是在簡單查詢的基礎上進行的。一 的合併 縱向增加 的合併或者說加法,是把兩個 加在一起,這個操作增加的是行,也就是說 會邊長。假設有個兩個表如下 表 course 表 course1 經過這個union 操作後,兩個表合...
sql數值求和
實際 select sum shuliang sum danjia sum jine as 單價 sum danjia as 單價,sum jine as 金額 from ang dbo myshucai 1 對列求和可以使用聚合函式sum,例如 select sum 金額 as 合計 from 表...
sql分組求和
需求是 乙個月有多個發布額,現在要求按月統計發布額,例如 1月發布額 35900,2月發布額 2300 sql 語句如下 按月分組,求和 select dmonth,codename,sum iamount from 求出全部日期,發布額 select convert varchar 7 a.dre...