在公用表表达式中使用更新

时间:2016-11-27 17:25:17

标签: sql postgresql

下面的

是CTE,它是更大查询的一部分。我试图尝试一些简单的事情:更新或替换' 2016-11'或者' 2016-12'值为' 2016-10。'

查询在UPDATE时遇到错误。这里有替代方案可以使这个查询起作用吗?

with q (month, cobrand, members) as
(select date_trunc('month',optimized_transaction_date), cobrand_id, 
count(distinct unique_mem_id)
from yi_fourmpanel.card_panel
Where (cobrand_id = '10001372' or cobrand_id = '10005640' or cobrand_id = '10005244') 
group by 1,2)

UPDATE q
SET members = dc
FROM (SELECT cobrand, members dc
      FROM q
      WHERE month = '2016-10') x
WHERE q.cobrand = x.cobrand
AND month IN ('2016-11', '2016-12')

1 个答案:

答案 0 :(得分:0)

如果您不想更改表格数据,请不要使用UPDATE

要实现您想要做的,请编写与此类似的主要查询:

WITH q(month, cobrand, members) AS (...)
SELECT
   month,
   cobrand,
   CASE WHEN month IN ('2016-11', '2016-12')
        THEN (SELECT members
              FROM q q1
              WHERE q1.month = '2016-10')
        ELSE members
   END
FROM q;