【问题标题】:Arranging the data on the basis of column value根据列值排列数据
【发布时间】:2018-04-18 15:03:29
【问题描述】:

我有一个具有以下结构的表。

+ ----------+--------------+--------+ |时间戳 |价值 |类型 | + ----------+--------------+--------+ | '2010-01-14 00:00:00' | '11787.3743' | '意思' | | '2018-04-03 14:19:21' | '9.9908' | '标准' | | '2018-04-03 14:19:21' | '11787.3743' | '分钟' | + ----------+--------------+--------+

现在我想编写一个选择查询,我可以在其中根据类型获取数据。

+ ----------+--------------+------------ --+----------+ |时间戳 |平均类型 |最小类型 |标准类型 | + ----------+--------------+------------ --+----------+ | '2010-01-14 00:00:00' | '11787.3743' | | | | '2018-04-03 14:19:21' | | | '9.9908' | | '2018-04-03 14:19:21' | | '11787.3743 | | + ----------+--------------+------------ --+----------+

请帮助我如何通过编写查询在 postgres DB 中执行此操作。我还想仅以 10 分钟的间隔获取数据。

【问题讨论】:

  • 您使用的是哪个 DBMS?
  • 我不明白显示的结果。是什么让您选择这三个值?
  • @Aureate :我正在使用 postgres DB。
  • @ThorstenKettner:你现在能理解结果吗?
  • @iftekhariftekhar 由于 postgres 不支持 PIVOT 函数,我正在删除我的答案,但您可以使用 CROSSTAB 函数来获得所需的输出。

标签: sql postgresql pivot postgresql-9.4


【解决方案1】:

使用CASE ... WHEN ...:

with my_table(timestamp, value, type) as (
values
    ('2010-01-14 00:00:00', 11787.3743, 'mean'),
    ('2018-04-03 14:19:21', 9.9908, 'std'),
    ('2018-04-03 14:19:21', 11787.3743, 'min')
)
select 
    timestamp,
    case type when 'mean' then value end as mean_type,
    case type when 'min' then value end as min_type,
    case type when 'std' then value end as std_type
from my_table;

      timestamp      | mean_type  |  min_type  | std_type 
---------------------+------------+------------+----------
 2010-01-14 00:00:00 | 11787.3743 |            |         
 2018-04-03 14:19:21 |            |            |   9.9908
 2018-04-03 14:19:21 |            | 11787.3743 |         
(3 rows)

【讨论】:

  • 这看起来不像 OP 需要的输出,是吗? -1,因为这个解决方案没有帮助。
  • @klin : 我怎样才能使列 (mean_type/min_type/std_type) 动态并使用 concat 就像 ---- case mc.type when 'mean' then value end as concat(s.type ,'-',s.height,'-',s.boom_orientation_angle,'-',s.suffix,'mean'),
  • 我无法在这里使用 concat..请帮忙!
  • 这是不可能的,因为结果的结构(列的数量、名称和类型)必须在查询中严格定义。您可以使用动态 sql 来创建视图,例如在这个答案中:Turning arbitrarily many rows into columns in PostgreSQL.
  • @mathguy - 你会不会对你不理解的答案投票?
猜你喜欢
  • 2021-06-19
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
  • 2019-10-10
  • 1970-01-01
  • 1970-01-01
  • 2020-05-15
  • 2017-10-16
相关资源
最近更新 更多