SQL to add a summary row to MySQL result set

前端 未结 4 1496
感动是毒
感动是毒 2021-01-24 21:18

If I have a MySQL table such as:

I want to use SQL to calculate the sum of the PositiveResult column and also the NegativeResult colu

4条回答
  •  耶瑟儿~
    2021-01-24 21:33

    I'd recommend doing this at the presentation layer. To do something like this in SQL is also possible.

    create table test (
      keywordid int, 
      positiveresult decimal(10,2), 
      negativeresult decimal(10,2)
    );
    insert into test values 
    (1, 0, 0), (2, 1, -2.5), (3, 1.6, -1), (4, 1, -2);
    
    select * from (
        select keywordid, positiveresult, negativeresult
        from test
          union all
        select null, sum(positiveresult), sum(negativeresult) from test
    ) main
    order by
    case when keywordid is null then 1000000 else keywordid end;
    

    I added ordering using a arbitrarily high number if keywordid is null to make sure the ordered recordset can be pulled easily by the view for displaying.

    Result:
    +-----------+----------------+----------------+
    | keywordid | positiveresult | negativeresult |
    +-----------+----------------+----------------+
    |         1 |           0.00 |           0.00 |
    |         2 |           1.00 |          -2.50 |
    |         3 |           1.60 |          -1.00 |
    |         4 |           1.00 |          -2.00 |
    |      NULL |           3.60 |          -5.50 |
    +-----------+----------------+----------------+
    

提交回复
热议问题