只获取所有项目的小计

时间:2014-12-03 00:23:49

标签: mysql rollup

我试图将总和值移到右边而不是它在底部。

目前,我有这个问题:

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

输出是:

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

我有办法这样做吗?

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

2 个答案:

答案 0 :(得分:0)

SELECT product,
       total_items,
       null as Subtotal
FROM items
WHERE inv = "ABC"
union all
select null, null, SUM(total_items) from items 

答案 1 :(得分:0)

好的,我想通了,谢谢你建议联盟。 我这样做了

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"

输出:

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

:)