我有一些看起来像这样的数据
ID |Name | Label1| Data1 |L2 |D2 |L3 | D3|
AAAA | C | X | 2 | Y | 4 | | |
BBBB | D | Y | 5 | Z | 6 | | |
CCCC | E | X | 3 | Y | 6 | Z | 9 |
DDDD | F | Z | 5 | X | 6 | Y | 3 |
我需要在报告上显示它:
ID |Name | X | Y | Z |
AAAA | C | 2 | 4 | 0 |
BBBB | D | 0 | 5 | 6 |
CCCC | E | 3 | 6 | 9 |
DDDD | F | 6 | 3 | 5 |
我该怎么做呢?
答案 0 :(得分:0)
您可以在SQL中透视数据:
-- load test data
declare @YourTable table(ID char(4),Name char(1),L1 char(1),D1 int,L2 char(1),D2 int,L3 char(1),D3 int)
insert into @YourTable values
('AAAA','C','X',2,'Y',4,null,null),
('BBBB','D','Y',5,'Z',6,null,null),
('CCCC','E','X',3,'Y',6,'Z',9),
('DDDD','F','Z',5,'X',6,'Y',3)
-- return pivoted data
select
ID,
Name,
isnull([X],0) [X],
isnull([Y],0) [Y],
isnull([Z],0) [Z]
from (
select
yt.ID,
yt.Name,
ld.Label,
ld.Data
from @YourTable yt
cross apply (
select L1 Label,D1 Data union all
select L2 Label,D2 Data union all
select L3 Label,D3 Data
) ld
) t
pivot (
max(Data)
for Label in([X],[Y],[Z])
) p