将选择的查询组合到更新中

时间:2016-03-20 13:58:44

标签: sql postgresql subquery

我有一张包含数据的表格,所以我不必动手做。但我必须经常更新表格。该表开始变大(700行),有时需要更新记录。

我目前有一组9个查询来更新表格,我确定有一种方法可以在一个查询中进行,但我不知道: 以下是我到目前为止的查询:

UPDATE checkouts SET total_colors = i.count_result,  FROM (SELECT COUNT(*) AS count_result FROM "checkouts" WHERE class != 'green' OR class is null) i WHERE i.id = checkouts.id
UPDATE checkouts SET sum_red = i.sum_result,  FROM (SELECT SUM("checkouts"."total_workers") AS sum_result FROM "checkouts" WHERE "checkouts"."class" = 'red') i WHERE i.id = checkouts.id
UPDATE checkouts SET sum_red = i.sum_result,  FROM (SELECT SUM("checkouts"."total_workers") AS sum_result FROM "checkouts" WHERE "checkouts"."class" = 'blue') i WHERE i.id = checkouts.id
UPDATE checkouts SET sum_red = i.sum_result,  FROM (SELECT SUM("checkouts"."total_workers") AS sum_result FROM "checkouts" WHERE "checkouts"."class" = 'yellow') i WHERE i.id = checkouts.id
UPDATE checkouts SET sum_red = i.sum_result,  FROM (SELECT SUM("checkouts"."total_workers") AS sum_result FROM "checkouts" WHERE "checkouts"."class" = 'black') i WHERE i.id = checkouts.id
UPDATE checkouts SET green_count = i.count_result,  FROM (SELECT COUNT(*) AS count_result FROM "checkouts" WHERE "checkouts"."company_id" = 113432 AND class = 'green') i WHERE i.id = checkouts.id
UPDATE checkouts SET code = i.code,  FROM (SELECT code FROM greens where code is not null GROUP BY code ORDER BY COUNT(code) DESC LIMIT 1) i WHERE i.company_id = checkouts.company_id
UPDATE checkouts SET code = i.email,  FROM (SELECT email FROM greens where email is not null GROUP BY email ORDER BY COUNT(email) DESC LIMIT 1) i WHERE i.company_id = checkouts.company_id
UPDATE checkouts SET total_workers = i.sum_result,  FROM (SELECT SUM("checkouts"."total_workers") AS sum_result FROM checkouts) i WHERE i.id = checkouts.company_id

1 个答案:

答案 0 :(得分:0)

您不应将摘要值存储在详细记录中(除非您确实知道自己在做什么)。一种可能性是在查询表时进行计算:

SELECT c.*,
       SUM(CASE WHEN class <> 'green' OR class is null THEN 1 ELSE 0 END) OVER (PARTITION BY id),
       SUM(CASE WHEN class = 'red' THEN 1 ELSE 0 END) OVER (PARTITION BY id) as total_red,
       . . . 
FROM checkouts;

事实上,您的数据结构看起来完全不合适。如果我不得不猜测,您在checkouts中有行项目详细信息,并且您正在尝试添加order-level摘要。您应该为此目的准备多个表。这些通常称为OrdersOrderLines