【问题标题】:Display sum of rows with same attribute, in new row below each group在每组下方的新行中显示具有相同属性的行总和
【发布时间】:2022-01-13 09:06:26
【问题描述】:

我有一张餐厅表:

name year profit
restaurant1 2016 112000
restaurant1 2018 150000
restaurant1 2020 165000
restaurant2 2018 40000
restaurant2 2019 52000
restaurant3 2017 64000
restaurant3 2018 73000
restaurant3 2019 76000

我想按餐厅名称对每家餐厅的利润求和,并在每家餐厅之后显示总利润,如下所示:

name year profit
restaurant1 2016 112000
restaurant1 2018 150000
restaurant1 2020 165000
restaurant1 total 427000
restaurant2 2018 40000
restaurant2 2019 52000
restaurant 2 total 92000
restaurant3 2017 64000
restaurant3 2018 73000
restaurant3 2019 76000
restaurant3 total 231000

我知道我可以通过SELECT SUM(profit) FROM restaurants GROUP BY restaurants.name;

获得每家餐厅的总利润

我的问题是如何显示此结果我在第二个表中显示的方式。

【问题讨论】:

    标签: database postgresql


    【解决方案1】:

    只需使用UNION

    SELECT name, year :: text, profit FROM restaurants
    UNION
    (SELECT name, 'total', SUM(profit) FROM restaurants GROUP BY restaurants.name)
    ORDER BY name, year
    

    dbfiddle查看结果

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-11
      • 2018-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多