SQL to add a summary row to MySQL result set

前端 未结 4 1457
感动是毒
感动是毒 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:32

    I would also do this in the presentation layer, but you can do it MySQL...

    DROP TABLE IF EXISTS my_table;
    
    CREATE TABLE my_table
    (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    ,pos DECIMAL(5,2)
    ,neg DECIMAL(5,2)
    );
    
    INSERT INTO my_table VALUES
    (1,0,0),
    (2,1,-2.5),
    (3,1.6,-1),
    (4,1,-2);
    
    
    SELECT COALESCE(id,'total') my_id,SUM(pos),SUM(neg) FROM my_table GROUP BY id WITH ROLLUP;
    
    +-------+----------+----------+
    | my_id | SUM(pos) | SUM(neg) |
    +-------+----------+----------+
    |     1 |     0.00 |     0.00 |
    |     2 |     1.00 |    -2.50 |
    |     3 |     1.60 |    -1.00 |
    |     4 |     1.00 |    -2.00 |
    |  total|     3.60 |    -5.50 |
    +-------+----------+----------+
    5 rows in set (0.02 sec)
    

    Here's a hack for the amended problem - it ain't pretty but I think it works...

    SELECT COALESCE(id,'') my_id
         , SUM(pos)
         , SUM(neg)
         , COALESCE(string,'') n
      FROM my_table 
     GROUP 
        BY id
         , string
      WITH ROLLUP
    HAVING n <> '' OR my_id = ''
    ;
    

提交回复
热议问题