将多个select和update子句截断为单个子句

时间:2016-11-13 13:25:56

标签: sql postgresql

以下查询似乎效率低下,因为我正在做的是为每个查询交换一个变量(cobrand)。有没有办法将此查询合并到一个子句中并获得相同的结果?

UPDATE temp_08.members
SET distinct_count=
(select distinct_count
from temp_08.members
WHERE cobrand='10001372' and month = '2016-09')
WHERE cobrand='10001372' and month = '2016-10' or month = '2016-11';


UPDATE temp_08.members
SET distinct_count=
(select distinct_count
from temp_08.members
WHERE cobrand='10006164' and month = '2016-09')
WHERE cobrand='10006164' and month = '2016-10' or month = '2016-11';



UPDATE temp_08.members
SET distinct_count=
(select distinct_count
from temp_08.members
WHERE cobrand='10005640' and month = '2016-09')
WHERE cobrand='10005640' and month = '2016-10' or month = '2016-11';



UPDATE temp_08.members
SET distinct_count=
(select distinct_count
from temp_08.members
WHERE cobrand='10005244' and month = '2016-09')
WHERE cobrand='10005244' and month = '2016-10' or month = '2016-11';

1 个答案:

答案 0 :(得分:1)

使用Postgres的update-with-join语法:

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

如果您只想更新某些品牌,可以将其添加到内部查询中:

AND cobrand IN ('10001372', '10006164', '10005640', '10005244')