我有一个值表,如下所示:
+--------+----+--------+
| Client | ID | Amount |
+--------+----+--------+
| A | 1 | 100 |
| B | 2 | 10 |
| C | 1 | 80 |
| C | 2 | 15 |
| D | 2 | 20 |
| E | 1 | 75 |
| E | 2 | 10 |
| F | 1 | 90 |
+--------+----+--------+
我想要做的是能够在此表上报告根据ID拆分的金额列值,所以它看起来像这样:
+--------+------+------+
| Client | ID 1 | ID 2 |
+--------+------+------+
| A | 100 | |
| B | | 10 |
| C | 80 | 15 |
| D | | 20 |
| E | 75 | 10 |
| F | 90 | |
+--------+------+------+
我猜关键是客户端同时拥有ID 1和2,它将出现在一行而不是多行。
任何关于如何做到这一点的想法都将受到赞赏。
答案 0 :(得分:2)
你可以在...... construct
时使用Sum case进行条件求和Select
Client
, ID1 = Sum(case when ID = 1 then Amount ELSE NULL end)
, ID2 = Sum(case when ID = 2 then Amount ELSE NULL end)
From MyTable
Group by Client
答案 1 :(得分:1)
/*
sql server 2012
the code below can run at above 2000
*/
set nocount on
;with sourceData as
(
select *
from (values('A',1,100),
('B',2,10),
('C',1,80),
('C',2,15),
('D',2,20),
('E',1,75),
('E',2,10),
('F',1,90))as b(Client,ID,Amount)
)
select Client,[1] as ID1,[2] as ID2
from sourceData as a pivot(max(Amount) for ID in([1],[2]))AS b
/*
Client ID1 ID2
------ ----------- -----------
A 100 NULL
B NULL 10
C 80 15
D NULL 20
E 75 10
F 90 NULL
*/