【问题标题】:How to added values in grouped column/rows using Postgres如何使用 Postgres 在分组的列/行中添加值
【发布时间】:2021-10-07 07:24:58
【问题描述】:

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

417 + 21 = 438 在一行

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

【问题讨论】:

    标签: sql postgresql group-by


    【解决方案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。

    【讨论】:

    • 非常感谢我一直在寻找的东西,只是你的改变很少@
    • @Mohamed。 . .我删除了where 子句。我不明白它的目的,但它在小提琴中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-18
    相关资源
    最近更新 更多