【问题标题】:Pervasive pivot data普遍的枢轴数据
【发布时间】:2019-03-08 14:15:00
【问题描述】:

我有一张表格,里面有以下数据

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

【问题讨论】:

  • 您的查询是什么样的?什么版本的 PSQL?

标签: sql pervasive pervasive-sql


【解决方案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;

【讨论】:

  • 这里是如何使用 PIVOT... 选择 ID ,[1] 作为 Label1 ,[2] 作为 Label2 ,[3] 作为 Label3 from #test pivot (sum (Value) for LabelID在 ([1],[2],[3])) 作为 XYX
  • Pervasive PSQL 不支持 PIVOT。
  • 直到现在我才听说过 Pervasive SQL。我发布的示例/样式是否适用于 PSQL?我想应该吧? mirtheil,您的查询也适用于 SQL Server。根据 SQL Server 执行计划,它需要 3 个嵌套循环,而我发布的示例中没有。
  • 酷 ?,总是令人耳目一新,看看 sql 的便携性。
  • 这个运行得又快又好!谢谢你的回答!
【解决方案2】:

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

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

【讨论】:

  • 试过这个并且成功了,但是加载数据需要很长时间(4个选择需要太多时间)
猜你喜欢
  • 2017-06-10
  • 1970-01-01
  • 2017-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多