【发布时间】:2021-10-07 07:24:58
【问题描述】:
我需要一些帮助才能将表 final_price 值相互添加,其中 customer_name/customer_id 相同,因此行数变为 3,例如:名为 Hass H final_price 的客户将是:
417 + 21 = 438 在一行
【问题讨论】:
标签: sql postgresql group-by
我需要一些帮助才能将表 final_price 值相互添加,其中 customer_name/customer_id 相同,因此行数变为 3,例如:名为 Hass H final_price 的客户将是:
417 + 21 = 438 在一行
【问题讨论】:
标签: sql postgresql group-by
您可以使用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。
【讨论】:
where 子句。我不明白它的目的,但它在小提琴中。