0

我正在使用 AWS redshift,它使用 PostgreSQL 作为 sql 语言。我需要一些帮助来形成我的查询以将数据非规范化为一行。

我的架构

Milestone
  -ItemId
  -LocationType //mapped to enum X, Y, Z
  -EventTime

Milestone 可以具有三种类型的位置 X、Y 或 Z。我想将其非规范化为一行。

ItemId EventTime_X EventTime_Y EventTime_Z

我已经尝试过这样的事情,但它只需要永远运行。

select x.itemId, X.eventTime as EventTime_X, Y.eventTime as EventTime_Y, z.eventTime as EventTime_Z
from (select * from milestone where LocationType = 'X') as X
left outer join (select * from milestone where LocationType = 'Y') as Y on x.itemId=y.itemId
left outer join (select * from milestone where LocationType = 'Z') as Z on x.itemId=z.itemId
4

1 回答 1

1

假设 X、Y 和 Z 有一个里程碑,您可以使用条件聚合来做到这一点:

select m.itemId,
       max(case when m.LocationType = 'X' then eventTime end) as eventTime_X,
       max(case when m.LocationType = 'Y' then eventTime end) as eventTime_Y,
       max(case when m.LocationType = 'Z' then eventTime end) as eventTime_Z
from Milestone m
where LocationType in ('X', 'Y', 'Z')
group by m.itemId;
于 2013-09-17T03:16:51.953 回答