[英]SQL query to sum two different values of same ID column in one query
友善的,有人可以幫我嗎,我有下表:
表名稱:余額
cname amount type
--------------------------------------
Jhon 150 A
Jhon 200 B
Jhon 100 A
Jhon 30 A
Jhon 55 B
=====================================
我想要一個SQLquery給我這個結果:
cname totalOf_A totalOf_B
---------------------------------------
Jhon 280 255
=========================================
我嘗試了以下方法:
select ,cname,sum(amount),type from balances group by cname,type
結果:
cname amount type
---- ----- ----
Jhon 250 A
Jhon 255 B
因此,我希望將結果放在一行中並在一個查詢中。
有任何建議請。
提前致謝。
您嘗試做的事情稱為條件聚集。 您可以使用
select
cname,
sum(case when type='A' then amount else 0 end) as total_A,
sum(case when type='B' then amount else 0 end) as total_B
from balances
group by cname
聽起來您好像要使用PIVOT。 在文檔中有一些示例。
https://technet.microsoft.com/zh-CN/library/ms177410(v=sql.105).aspx
select A.cname,A.typeof_A,B.typeof_B
FROM
(
select cname,sum(amount) as typeof_A
from balances
where type = 'A'
group by cname
) as A
INNER JOIN
(
select cname,sum(amount) as typeof_B
from balances
where type = 'B'
group by cname
) as B
ON B.cname = A.cname
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.