简体   繁体   中英

Using Update in a Common Table Expression

below is a CTE that is part of a larger query. I am trying to attempt something simple: update or replace all records for '2016-11' or '2016-12' values with '2016-10.'

The query runs into an error at UPDATE. Is there an alternative here that would make this query work?

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')

If you don't want to change table data, don't use UPDATE .

To achieve what you want to do, write the main query similar to this:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM