SQL分隔一个组并添加引用它们的值

时间:2018-09-08 22:54:12

标签: sql sql-server

我有一个表格,表格中的类别为“ P”-支付,“ R”-收款,“ C”-贷项,并且类别具有其值...采用以下格式

Money | Category
5         P
10        R
5         R
20        C
15        P

并获得我的sql结果

P  | R | C
20 | 15| 20

如何创建一个SQL来生成这3列而不必执行3个子查询?

select sum(money) from accounts -- that adds up all

select 
(select sum(money) from caixa where category= 'R' ) as 'CR',
(select sum(money) from caixa where category= 'P  ) as 'CP' 
from accounts -- this even works, but it returns me several lines with the same information

2 个答案:

答案 0 :(得分:1)

您可以尝试使用条件汇总函数而不是子查询。

CREATE TABLE caixa (
   Money int,
   Categoty varchar(5)
);

insert into caixa  values (5,'P');
insert into caixa  values (10,'R');
insert into caixa  values (5,'R');
insert into caixa  values (20,'C');
insert into caixa  values (15,'P');

查询

select  sum(CASE WHEN Categoty = 'P' then money else 0 end) P, 
        sum(CASE WHEN Categoty = 'R' then money else 0 end) R, 
        sum(CASE WHEN Categoty = 'C' then money else 0 end) C
from caixa 
WHERE Categoty IN ('P','R','C')

sqlfiddle

答案 1 :(得分:0)

另一个选择是PIVOT

示例

Select * 
 From (
       Select [Money]
             ,[Category] 
         From Accounts 
      ) src
 Pivot ( sum([Money]) for [Category] in ([P],[R],[C]) ) pvt

返回

P   R   C
20  15  20