2016-11-13 8 views
2

以下のクエリは効率的ではありません。すべてのクエリで1つの変数(cobrand)を交換するだけです。このクエリを1つの節に統合して同じ結果を得る方法はありますか?複数のselect節とupdate節を1つの節に切り捨てます

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