PostgreSQL - making first row show as total of other rows

后端 未结 3 1568
萌比男神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:38

    You can avoid a second full scan of the table with a CTE:

    PostgreSQL 9.2 Schema:

    create table basket(fruits text, a integer, b integer, c integer);
    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:

    with w as ( select fruits, sum(a) a, sum(b) b, sum(c) c
                from basket
                group by fruits )
    select * from w union all select 'total', sum(a), sum(b), sum(c) from w
    

    Results:

    |  FRUITS | A | B | C |
    -----------------------
    | bananas | 1 | 1 | 2 |
    | oranges | 1 | 1 | 1 |
    |  apples | 1 | 2 | 3 |
    |   total | 3 | 4 | 6 |
    

    SQL Fiddle here

提交回复
热议问题