Postgres Update列与另一行数据

时间:2013-05-09 15:16:55

标签: sql database postgresql join

好的我有两张桌子

measures
attr_id, period, net_orders, ref_1 (key = attr_id,period)

policy
attr_id, lead_time 

我需要做的是从句点中获取'net_orders'(这是一个日期),添加'lead_time'并更新度量表'ref_1',其中period = period + lead

我目前有选择能够获取我需要的数据,但在尝试找出where子句时,我一直在迷失自己。

SELECT 
  m.attr_id, 
  m.period, 
  m.net_orders, 
  p.lead_time,
  DATE(m.period) + CAST(p.lead_time as INTEGER) as updateperiod
FROM 
  measures m 
  INNER JOIN policy p ON p.attr_id = m.attr_id

我遇到了以下一些问题 - 又名不完整

UPDATE
  measures m
SET
  ref_1 = (SELECT m1.net_orders FROM measures m1 
           WHERE m1.attr_id = m.attr_id AND m1.period = m.period)
WHERE
  attr_id = (SELECT m3.attr_id 
             FROM measures m3 WHERE m3.attr_id = m.attr_id   
             AND m3.period = m.period)
  AND m.period = (SELECT DATE(m2.period) + CAST(p2.lead_time AS INTEGER) 
             FROM measures m2 INNER JOIN policy p2 ON p2.attr_id = m2.attr_id
             WHERE m2.attr_id = m.attr_id AND m2.period = m.period)

修改

update measures m
set reference_1 = s.net_orders
from (
    select
        m.attribute_id, period, net_orders,
        DATE(period) + CAST(lead_time as integer) as periodlevel
    from
        measures m
        inner join policies p on p.attribute_id = m.attribute_id
) s
where
    m.attribute_id = s.attribute_id
    and m.period = s.periodlevel

这是最终起作用的查询。我在第一个回答时遇到错误但看起来现在正在运行!

1 个答案:

答案 0 :(得分:1)

update measures m
set ref_1 = s.net_orders
from (
    select
        m.attr_id, period, net_orders,
        period::date + lead_time::int period
    from
        measures m
        inner join
        policy using(attr_id)
) s
where
    s.attr_id = m.attr_id
    and s.period = m.period::date