繁体   English   中英

普适数据

[英]Pervasive pivot data

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

 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM