MySQL only get overall ROLLUP

后端 未结 3 529
轻奢々
轻奢々 2021-01-20 02:23

Performing a WITH ROLLUP when grouping by multiple fields, MySQL returns a rollup row for each group, as well as the overall summary:

CREATE TAB         


        
相关标签:
3条回答
  • 2021-01-20 03:03

    Try to use a subquery, e.g. -

    SELECT * FROM (
      SELECT name, number, COUNT(1) FROM test GROUP BY name, number WITH ROLLUP) t
    WHERE name IS NULL OR number IS NULL
    

    You also may want to change NULL values with appropriate texts.

    0 讨论(0)
  • 2021-01-20 03:11
    SELECT COALESCE(name, 'TOTAL') as Name, number, COUNT(1) FROM test GROUP BY name, number WITH ROLLUP;
    

    Below Name column it would Display as Total. If you have issue with number as null same can be done for that too.

    0 讨论(0)
  • 2021-01-20 03:12

    HAVING can do the trick with no subquery:

    SELECT `name`, number, COUNT(1) FROM test GROUP BY `name`, number WITH ROLLUP 
    HAVING number IS NOT NULL OR `name` IS NULL;
    

    This filters out the post-rollup rows except for the grand total:

    name    number  COUNT(1)
    ------  ------  --------
    bar          1         1
    bar          2         4
    bar          3         1
    baz          1         1
    baz          2         1
    foo          1         2
    foo          2         1
    foo          3         2
    (NULL)  (NULL)        13
    
    0 讨论(0)
提交回复
热议问题