Search code examples
mysqlrollup

Only get the subtotal of all the items


I'm trying to move the sum value to the right instead of it being on the bottom.

Currently, I have this query:

SELECT

if(product is NULL, 'Total', product) as Product,

total_items as Total,
SUM(total_items) as Subtotal
FROM items

WHERE inv = "ABC"


GROUP BY product
WITH ROLLUP

Output of this is:

|   Product     |   Total   |   Subtotal    |
|   AB          |   260     |   260         |
|   DE          |   66      |   66          |
|   Total       |   66      |   326         |

Is there a way I can do it like this?

|   Product     |   Total   |   Subtotal    |
|   AB          |   260     |               |
|   DE          |   66      |               |
|               |           |   326         |

Solution

  • Ok I figured it out, thank you for suggesting the union all. I did it like this

    SELECT
    
    product,
    total_items as Total,
    null as Total
    
    FROM items
    
    WHERE inv = "ABC"
    
    GROUP BY product
    
    UNION ALL
    
    SELECT null, null, Subtotal
    FROM
    (   SELECT
    
        if(product is NULL, 'Subtotal', product) as Product,
        SUM(total_items) as Subtotal
    
        FROM items
    
        WHERE inv = "ABC"
    
    
        GROUP BY product
        WITH ROLLUP
    ) T
    WHERE product = "Subtotal"
    

    Output:

    |   Product     |   Total   |   Subtotal    |
    |   AB          |   260     |               |
    |   DE          |   66      |               |
    |               |           |   326         |
    

    :)