如何使用 Postgres 在分组的列/行中添加值

时间:2021-08-01 18:10:39

标签: sql postgresql group-by

我需要一些帮助来将表 final_price 值相互添加,其中 customer_name/customer_id 相同,因此行数变为 3,例如:名为 Hass H final_price 的客户将是:

417 + 21 = 438 一行

http://sqlfiddle.com/#!17/29cb5/13

1 个答案:

答案 0 :(得分:1)

您可以使用 grouping sets。我认为这可以满足您的要求:

SELECT c.first_name || ' ' || c.surname AS customer_name, 
       SUM(oi.quantity) AS number_of_items_bought,
       SUM(sp.price * oi.quantity) AS final_price
FROM customers c JOIN
     ordered_items oi
     ON oi.customers_id = c.id JOIN
     store_products sp
     ON sp.id = oi.store_products_id
GROUP BY GROUPING SETS ( (customer_name, sp.price), (customer_name) );

请注意,我删除了 HAVING(它似乎没有做任何事情)并修改了第二个 SUM()

Here 是 SQL Fiddle。