2016-11-13 40 views
2

下面的查询看起来效率不高,因为我所做的只是为每个查询换出一个变量(cobrand)。有没有办法将这个查询合并成一个子句并得到相同的结果?将多个select和update子句截断成单个子句

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'; 
+0

你有没有尝试使用'WHEN'子句? – FDavidov

回答

1

使用Postgres的更新与联接语法:

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

您可以添加这内查询,如果你只是想更新某些cobrands:

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