MySQL SUM分别与多个列组

时间:2015-06-22 08:32:38

标签: mysql

enter image description here

以下是查询的尝试:

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

但结果并不成功。

如何做到这一点,是否可以在一个查询中获得最终结果?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

使用 [HttpPost] public ActionResult Create(FileViewModel model) { if (ModelState.IsValid) { var image = new Image(); model.SaveAs(HttpContext.Server.MapPath("../../Content/img/upload/") + model.FileName); image.ImagePath = model.FileName; db.Images.Add(image); db.SaveChanges(); return RedirectToAction("Index"); } return RedirectToAction("Create", "Images"); }

with rollup

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

您可以轻松地将列名转换为:

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