2014-12-03 72 views
0

我試圖將總和值移到右邊而不是底部。只得到所有項目的小計

目前,我有這個疑問:

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   | 
+0

爲什麼不這樣做的MySQL – Sergey 2014-12-03 00:26:59

+0

呀之外 - 我真的不彙總的粉絲 – Strawberry 2014-12-03 00:45:33

回答

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   | 

:)

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