更新redshift表上的is_latest列

时间:2018-11-20 00:35:22

标签: sql amazon-redshift

我正在尝试使用以下更新语句更新由is_latestsource分组的redshift表上的source_primary_key列,但出现一个错误,指出不允许在其中使用窗口函数更新语句。最好的方法是什么?

update my_schema.production_log
set is_latest = 
case when run_start_time = max(run_start_time) over (partition by 
source,   source_primary_key)
then ‘t’ else ‘f’
end

2 个答案:

答案 0 :(得分:0)

Redshift在FROM语句中支持update子句。试试这个:

update my_schema.production_log
    set is_latest = (case when run_start_time = max_run_start_time
                          then 't' else 'f'
                     end)
    from (select source, source_primary_key, max(run_start_time) as max_run_start_time
          from my_schema.production_log
          group by source, source_primary_key
         ) pl2
    where pl2.source = production_log.source and
          pl2.source_primary_key = production_log.source_primary_key;

答案 1 :(得分:0)

您需要重写查询,以便它可以连接到派生表:

UPDATE u
SET u.is_latest =CASE
                     WHEN u.run_start_time = j.max_time THEN 't'
                     ELSE 'f'
                 END
FROM my_schema.production_log AS u
INNER JOIN (
    SELECT
        source
      , source_primary_key
      , MAX( run_start_time ) max_time
    FROM my_schema.production_log
    GROUP BY
        source
      , source_primary_key
) AS j
    ON u.source = j.source
    AND u.source_primary_key = j.source_primary_key