kindly, can someone help me with this, I have the following table:
亲切的,有人可以帮我这个,我有下表:
Table Name : balances
表名:余额
cname amount type
--------------------------------------
Jhon 150 A
Jhon 200 B
Jhon 100 A
Jhon 30 A
Jhon 55 B
======================================
======================================
I want an SQLquery gives me this result:
我想要一个SQLquery给我这个结果:
cname totalOf_A totalOf_B
---------------------------------------
Jhon 280 255
=========================================
I've tried the follwoing:
我尝试了以下内容:
select ,cname,sum(amount),type from balances group by cname,type
the result:
结果:
cname amount type
---- ----- ----
Jhon 250 A
Jhon 255 B
so, I want the result in one row and in one query please.
Any suggestions please.
Thanks in advance.
所以,我希望结果在一行和一个查询中。请给我任何建议。提前致谢。
3 个解决方案
#1
1
What you're trying to do is called conditional aggregation. You can use
你要做的是称为条件聚合。您可以使用
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
#2
0
It sounds like you are going to want to use a PIVOT. There are some examples in the docs.
听起来你会想要使用PIVOT。文档中有一些例子。
https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx
https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx
#3
0
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
#1
1
What you're trying to do is called conditional aggregation. You can use
你要做的是称为条件聚合。您可以使用
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
#2
0
It sounds like you are going to want to use a PIVOT. There are some examples in the docs.
听起来你会想要使用PIVOT。文档中有一些例子。
https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx
https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx
#3
0
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