普遍的枢轴数据

Pervasive pivot data

我有一个 table,其中包含以下数据

ID|LabelID|Value
1 |1      |3
1 |2      |1
1 |3      |15
2 |1      |5
2 |2      |7
2 |3      |5

我想在一个普遍的数据库中得到以下结果

ID|Label1|Label2|Label3
1 |3     |1     |15
2 |5     |7     |5

有人知道吗?我确实尝试了一些事情,我能得到的最好结果如下:

ID|Label1|Label2|Label3
1 |3     |      |
1 |      |1     |
1 |      |      |15
2 |5     |      |
2 |      |7     |
2 |      |      |5

玩得开心...:-)

应该适用于 SQL 的大多数版本。供应商特定的 PIVOT 语句也是一个选项。

这是在 PIVOT 子句之前执行此操作的方法。

drop table #test;
create table #test (ID int, LabelID int, Value int);

insert into #test values (1, 1, 3)
,(1, 2, 1)
,(1, 3, 15)
,(2, 1, 5)
,(2, 2, 7)
,(2, 3, 5);

select ID
      ,sum(case when LabelID = 1 then Value else null end) as Label1
      ,sum(case when LabelID = 2 then Value else null end) as Label2
      ,sum(case when LabelID = 3 then Value else null end) as Label3
  from #test
group by ID;

这是一个对我有用的查询。

create table psqlPivot (id integer, labelid integer, val integer);
insert into psqlPivot values (1, 1,3);
insert into psqlPivot values (1, 2,1);
insert into psqlPivot values (1, 3,15);
insert into psqlPivot values (2, 1,5);
insert into psqlPivot values (2, 2,7);
insert into psqlPivot values (2, 3,5);

select distinct v.id, (select a.val as label1 from psqlPivot a where a.labelid = 1 and a.id = v.id)
,(select b.val as label2 from psqlPivot b where b.labelid = 2 and b.id = v.id)
,(select c.val as label3 from psqlPivot c where c.labelid = 3 and c.id = v.id)
from psqlpivot v