2015-06-22 62 views
1

enter image description here多列組的MySQL SUM分別

下面是該查詢曾嘗試:

SELECT Actor, Country, Customer_Name, SUM(Revenue), (Employee_Number) 
FROM CUSTOMER 
GROUP BY Actor, Country; 

但結果並不成功。

如何做到這一點,是否有可能在一個查詢中得到最終結果?

回答

1

使用with rollup

select t1.a, t1.b, t1.c, t2.id 
from (select a, b, sum(c) c from t 
     group by a, b 
     with rollup) t1 
left join t t2 on t1.a = t2.a and t1.b = t2.b 
order by case when t1.a is null then 1 else 0 end, 
     t1.a, 
     case when t1.b is null then 1 else 0 end, 
     t1.b 

小提琴http://sqlfiddle.com/#!9/14df56/5

您可以很容易地將您的列名轉換爲:

a -> Actor 
b -> Country 
c -> Revenue 
id -> Costomer_Name, Employee_Number 
2

我認爲你可以使用UNION ALL這樣的:

SELECT 
    Actor, Country, Customer_Name, Revenue, Employee_Number 
FROM (
    SELECT Actor, Country, Customer_Name, SUM(Revenue) As Revenue, Employee_Number, Actor + Country + Customer_Name AS ord 
    FROM CUSTOMER 
    GROUP BY Actor, Country, Customer_Name, Employee_Number 
    UNION ALL 
    SELECT Actor, Country, 'SUM' AS Customer_Name, SUM(Revenue) As Revenue, SUM(Employee_Number) AS Employee_Number, Actor + Country + 'zzzzz' AS ord 
    FROM CUSTOMER 
    GROUP BY Actor, Country 
    UNION ALL 
    SELECT Actor, 'SUM' AS Country, 'SUM' AS Customer_Name, SUM(Revenue) As Revenue, SUM(Employee_Number) AS Employee_Number, Actor + 'zzzzzzzzzz' AS ord 
    FROM CUSTOMER 
    GROUP BY Actor) t 
ORDER BY 
    ord 

對於這樣的:

Actor | Country | Customer_Name | Revenue | Employee_Number 
--------+-----------+---------------+-----------+------------------- 
user1 | AUS  | qsd corp  | 60  | 20 
user1 | AUS  | xyz corp  | 50  | 5 
user1 | AUS  | SUM   | 110  | 25 
user1 | US  | abc corp  | 100  | 6 
user1 | US  | efg corp  | 200  | 10 
user1 | US  | SUM   | 300  | 16 
user1 | SUM  | SUM   | 410  | 41