SQL查询在一个查询

时间:2017-02-17 21:27:34

标签: mysql sql

亲切的,有人可以帮我这个,我有下表:

表名:余额

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    

所以,我希望结果在一行和一个查询中 请提出任何建议 提前致谢。

3 个答案:

答案 0 :(得分:1)

您要做的是称为条件聚合。你可以使用

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

答案 1 :(得分:0)

听起来你想要使用PIVOT。文档中有一些例子。

https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

答案 2 :(得分: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