MySQL: Get total in last row of MySql result

前端 未结 6 510
夕颜
夕颜 2020-12-10 04:29

For example I have a table like this:

product | quantity | something
-------------------------------
 abc    |   5      |  2
 xzy    |   5      |  2
 asd             


        
相关标签:
6条回答
  • 2020-12-10 04:55
    $q="select sum(quantity), sum(something) from tableName";
    
    0 讨论(0)
  • 2020-12-10 04:56

    it's not the best way to solve this but should do the trick

    select product, quantity, something from tableName
    union 
    select 'sum', sum(quantity), sum(something) from tableName
    
    0 讨论(0)
  • 2020-12-10 04:59

    Try to avoid union query it may increase the execution time in case of joins and case queries. So as @Chris Strickland said, use WITH ROLLUP.

    0 讨论(0)
  • 2020-12-10 05:02
    (SELECT product, 
            quantity, 
            something 
     FROM   tablename) 
    UNION 
    (SELECT "all"          AS product, 
            SUM(quantity)  AS quantity, 
            SUM(something) AS something 
     FROM   tablename) 
    

    This is working query. It will add a fourth row as desired at the end of your result

    0 讨论(0)
  • 2020-12-10 05:14

    You can use rollup to generate totals, but you have to change it to an aggregate function, like this:

    SELECT product, sum(quantity), sum(something)
    FROM tableName
    GROUP BY product WITH ROLLUP
    
    0 讨论(0)
  • 2020-12-10 05:18

    You could

    SELECT Product, Quantity, Something 
    FROM TABLENAME
    
    UNION
    
    SELECT 'ALL', SUM(Quantity),SUM(Something) 
    FROM TABLENAME
    

    This would not, however, add a row in your table. Which is probably not a good idea anyways.

    0 讨论(0)
提交回复
热议问题