PostgreSQL - making first row show as total of other rows

后端 未结 3 1514
萌比男神i
萌比男神i 2021-02-04 11:13

Is there any way to make first row be different then the rest, so it would show total sum of the appropriate columns?

For example:

      fruits|a|b|c
            


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-04 11:41

    This is now possible in version 9.5 of Postgres:

    PostgreSQL 9.5 Schema

    CREATE TABLE basket(fruits text, a integer, b integer, c integer);
    CREATE TABLE
    INSERT INTO basket(fruits, a, b, c) values('apples', 1, 1, 1),
                                          ('apples', 0, 1, 2),
                                          ('bananas', 1, 1, 2),
                                          ('oranges', 1, 1, 1);
    

    Query

    SELECT coalesce(fruits,'total'), sum(a) a, sum(b) b, sum(c) c
    FROM basket
    GROUP BY ROLLUP((fruits))
    

    Results

     fruits  | a | b | c
    ---------+---+---+---
     apples  | 1 | 2 | 3
     bananas | 1 | 1 | 2
     oranges | 1 | 1 | 1
     total   | 3 | 4 | 6
    

    This ROLLUP is equivalent to using an expressions with GROUPING SETS:

    SELECT fruits, sum(a) a, sum(b) b, sum(c) c
    FROM basket
    GROUP BY GROUPING SETS (fruits, ())
    

    Each sublist in the GROUPING SETS is interpreted the same way as though it were directly in the GROUP BY clause.

提交回复
热议问题