【问题标题】:How to convert row into column in PostgreSQL of below table如何在下表的PostgreSQL中将行转换为列
【发布时间】:2020-07-06 07:46:39
【问题描述】:

我试图将跟踪表转换为 postgress 中的结果表。我在表中有拥抱数据。

我有一个名称为:Trace 的表

entity_id                         | ts                | key         | bool_v  |   dbl_v |   str_v   | long_v  |
---------------------------------------------------------------------------------------------------------------
1ea815c48c5ac30bca403a1010b09f1   | 1593934026155   | temperature   |         |         |           | 45      |
1ea815c48c5ac30bca403a1010b09f1   | 1593934026155   | operation     |         |         |   Normal  |         |
1ea815c48c5ac30bca403a1010b09f1   | 1593934026155   | period        |         |         |           | 6968    |
1ea815c48c5ac30bca403a1010b09f1   | 1593933202984   | temperature   |         |         |           | 44      |
1ea815c48c5ac30bca403a1010b09f1   | 1593933202984   | operation     |         |         |   Reverse |         |
1ea815c48c5ac30bca403a1010b09f1   | 1593933202984   | period        |         |         |           | 3535    |

Trace Table

在PostgreSQL中将上表转换为下表

输出表:结果

entity_id                         | ts            | temperature | operation | period    |
----------------------------------------------------------------------------------------|
1ea815c48c5ac30bca403a1010b09f1   | 1593934026155 | 45          | Normal    | 6968      |
1ea815c48c5ac30bca403a1010b09f1   | 1593933202984 | 44          | Reverse   | 3535      |

Result Table

【问题讨论】:

标签: postgresql join pivot


【解决方案1】:

你试过了吗?

select entity_id, ts,
       max(long_v) filter (where key = 'temperature') as temperature,
       max(str_v) filter (where key = 'operation') as operation,
       max(long_v) filter (where key = 'period') as period
  from trace
 group by entity_id, ts;

【讨论】:

  • 感谢您的回复。是的,我试过了,但存在性能问题。我有数十亿的数据,所以我希望优化的查询能够更快地处理数据。
  • @PavankumarBehere 您的表是否已编入索引,或者是否有主键?除非temperatureoperationperiod 之外还有许多key 值,否则我想不出更快的方法来执行此转换。即便如此,拥有尽可能多的数据,构建索引将花费很长时间并消耗大量空间。如果ts 对您的分析至关重要,您是否考虑过像timescale.com 这样的解决方案?
猜你喜欢
  • 2019-10-15
  • 1970-01-01
  • 1970-01-01
  • 2015-09-11
  • 1970-01-01
  • 1970-01-01
  • 2012-12-14
  • 1970-01-01
  • 2021-05-16
相关资源
最近更新 更多