PostgreSQL非规范化查询

时间:2013-09-17 03:11:39

标签: sql postgresql

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

我的架构

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

里程碑可以有三种类型的位置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

1 个答案:

答案 0 :(得分: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;