【问题标题】:Postgres/AWS Redshift: Pivot data to column long formPostgres/AWS Redshift:将数据透视到列长格式
【发布时间】:2017-09-19 11:12:26
【问题描述】:

我目前有一些如下表格的数据。

userid |      event_time      | event_duration (secs) | first_activity | last_activity
   A      2017-01-01 02:20:34             16               E1                 E2     
   A      2017-03-01 11:23:43             12               E2                 E6
   B      2017-01-01 08:24:32             53               E1                 E4
   C      2017-01-01 23:19:21             43               E3                 E11

我想把它变成表格:

userid |      event_time      | activity
   A      2017-01-01 02:20:34      E1
   A      2017-01-01 02:20:50      E2     
   A      2017-03-01 11:23:43      E2                
   A      2017-03-01 11:23:55      E6
   B      2017-01-01 08:24:32      E1                
   B      2017-01-01 08:25:25      E4
   C      2017-01-01 23:19:21      E3                
   C      2017-01-01 23:20:04      E11

我可以很容易地做到这一点:

SELECT userid, event_time, first_activity
FROM table
UNION
SELECT userid, event_time + event_duration * interval '1 seconds', last_activity
FROM table

但是,我想要一种避免使用UNIONs 重复查询两次的方法。有没有一种简洁的方法来创建我需要的表单而无需UNIONing 两个查询?

【问题讨论】:

  • 如果您使用 Redshift,请勿使用 Postgres 标记问题。 From the Redshift manual: "不要假设 Amazon Redshift 和 PostgreSQL 的共同元素的语义是相同的"

标签: sql join subquery amazon-redshift


【解决方案1】:

仅在编写此答案时,该问题才使用 Postgres 标记。

您可以使用横向连接:

select v.*
from t, lateral
     (values (t.userid, t.eventtime, t.first_activity),
             (t.userid, t.eventtime + t.event_duration * interval '1 second', t.last_activity)
     ) v(userid, eventtime, activity);

作为编辑说明。不用逗号也可以这样写:

select v.*
from t cross join lateral
     (values (t.userid, t.eventtime, t.first_activity),
             (t.userid, t.eventtime + t.event_duration * interval '1 second', t.last_activity)
     ) v(userid, eventtime, activity);

, lateral 是我实际上更喜欢FROM 子句中的逗号的一种情况。有趣的是,SQL Server 使用APPLY 关键字进行横向连接。 Oracle 同时支持LATERALAPPLY

【讨论】:

  • Oracle 从 12.1 开始支持横向:slideshare.net/MarkusWinand/modern-sql/11
  • @MarkusWinand 。 . .谢谢。
  • @GordonLinoff:不幸的是,使用, lateralv(userid, eventime, activity) 上会出现以下错误:function values(character varying, timestamp without time zone, character varying) does not exist
  • @Black 。 . .您使用的是什么版本的 Postgres?我相信横向是在 9.3 中引入的。
  • @GordonLinoff,我使用的是基于 8.0 版本的 Redshift。
猜你喜欢
  • 2022-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-04
  • 1970-01-01
  • 1970-01-01
  • 2017-07-13
  • 1970-01-01
相关资源
最近更新 更多