普遍的数据透视

时间:2019-03-08 14:15:01

标签: sql pervasive pervasive-sql

我有一张桌子,里面有以下数据

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

2 个答案:

答案 0 :(得分:1)

玩得开心... :-)

在大多数版本的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;

答案 1 :(得分:1)

这是对我有用的查询。

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