简体   繁体   English

SQL查询在一个查询中求和同一ID列的两个不同值

[英]SQL query to sum two different values of same ID column in one query

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. 提前致谢。

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

It sounds like you are going to want to use a PIVOT. 听起来您好像要使用PIVOT。 There are some examples in the docs. 在文档中有一些示例。

https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM