SQL子查询得到总数

时间:2018-03-20 11:44:32

标签: mysql sql mysql-workbench categorical-data

使用SQL子查询,如何获得包括其团队在内的每位经理的总项目和总收入? 假设我有这个表items_revenue列: enter image description here

所有经理(is_manager = 1)及其各自的成员都在上表中。 Member1在Manager1下,Member2在Manager2下,依此类推,但实际数据是随机排列的。

我希望我的查询输出ff。:

enter image description here

这与SQL query to get the subtotal of some rows有关,但我不想使用CASE表达式。谢谢!

您可以复制此内容以轻松创建表格:

DROP TABLE IF EXISTS items_revenue;
CREATE TABLE items_revenue (id int, is_manager int, manager_id int, name varchar(55), no_of_items int, revenue int);
INSERT INTO items_revenue (id, is_manager, manager_id, name, no_of_items, revenue)
VALUES
    (1  ,    1     ,    0     , 'Manager1' ,    621    ,   833), 
    (2  ,    1     ,    0     , 'Manager2' ,    458    ,   627),
    (3  ,    1     ,    0     , 'Manager3' ,    872    ,   1027 ),
    (8  ,    0     ,    1     , 'Member1'  ,    1258   ,   1582),
    (9  ,    0     ,    2     , 'Member2'  ,    5340   ,   8827),
    (10  ,    0     ,    3     , 'Member3'  ,    3259   ,   5124);

3 个答案:

答案 0 :(得分:4)

使用union all和aggreation:

select manager_id, sum(no_of_items) as no_of_items, sum(revenue) as revenue
from ((select ir.manager_id, ir.no_of_items, ir.revenue
       from items_revenue ir
       where ir.is_manager = 0
      ) union all
      (select ir.id, ir.no_of_items, ir.revenue
       from items_revenue ir
       where ir.is_manager = 1
      )
     ) irm
group by manager_id;

注意:这仅处理表中的直接报告。这是您提供的示例数据。如果您需要所有直接报告,问题会有很大不同,因此请不要针对这种情况修改此问题(询问另一个问题)。如果这是你的需要,那么MySQL不是最好的工具(除非你使用的是版本8),尽管如果你知道最大深度就可以解决它。

答案 1 :(得分:1)

使用两个子查询,一个按id分组,is_manager=1分组,另一个分组manager_id is_manager=0

SELECT id, name, 
       (t1.total_items + t2.total_items) total_items,
       (t1.total_revenue + t2.total_revenue) total_revenue
FROM (SELECT id, name, 
             sum(no_of_items) total_items, 
             sum(revenue) total_revenue
      FROM   items_revenue
      WHERE  is_manager = 1
      GROUP BY id, name) t1
JOIN (SELECT manager_id,
             sum(no_of_items) total_items, 
             sum(revenue) total_revenue
      FROM   items_revenue
      WHERE  is_manager = 0
      GROUP BY manager_id) t2
ON    t1.id = t2.manager_id;

Rextester here

答案 2 :(得分:0)

SELECT
  employee.totalit + items_revenue.no_of_items,
  employee.totalerev + items_revenue.revenue,
  employee.manager_id
FROM (SELECT
        sum(no_of_items) AS totalit,
        sum(revenue) as totalerev,
        manager_id
      FROM items_revenue
      WHERE manager_id <> 0
      GROUP BY manager_id) AS employee, items_revenue
WHERE items_revenue.user_id = employee.manager_id;