我有一个像这样的简单表格
time_stamp, metric, value
2012/3/2 , x , 1
2012/3/2 , y , 1.6
2012/3/3 , x , 0
2012/3/3 , y , null
...
我想写一个返回类似内容的查询
time_stamp, x, y
2012/3/2 , 1, 1.6
2012/3/3 , 0, null
换句话说,基本上是根据一个字段的唯一值即时生成列,并将数据重新整形到其中。
我记得我在哪里见过它,但我现在找不到了。
附言。我现在正在使用 PostgreSQL。请注意该解决方案是否特定于特定的 DBMS。
更新:从中形成列的指标值是动态的。我知道这使这变得更加困难,而且几乎不可能使用单个查询解决方案。
根据评论,我也尝试过交叉表,它 a) 非常特定于 pg,b) 不太适合动态表数。
最佳答案
使用条件聚合
转置行。
select time_stamp,
max(case when metric= 'X' then value End) as X,
max(case when metric= 'Y' then value End) as Y,
From Yourtable
group by time_stamp
关于sql - 在 SQL 中 reshape 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28483895/