如何在SQL中汇总不同的条件?

时间:2018-08-09 21:46:38

标签: sql amazon-redshift

我在Redshift中有如下数据:

+-------------+------------+---------+
| Employee_ID | Manager_ID | Revenue |
+-------------+------------+---------+
|         123 |        123 | 1015.24 |
|         541 |        123 | 5587.23 |
+-------------+------------+---------+

我想编写一个查询,该查询将在输入Manager_ID时对经理收入进行汇总,并在输入Employee_ID时对员工收入进行汇总。当前,我有一个查询,看起来像这样,我必须运行两次:

SELECT      
  sum(revenue) as revenue
FROM 
  employee_rev r
WHERE
  r.manager_id in ('123','124') --I change this to employee_ID the second time around

如果有帮助,还有另一个这样的表:

+-------------+------------------------+
| Employee_ID |          Role          |
+-------------+------------------------+
|         123 | Manager                |
|         541 | Individual Contributor |
+-------------+------------------------+

非常感谢您抽出宝贵的时间,这似乎很简单,现在我很沮丧。

2 个答案:

答案 0 :(得分:1)

我认为您可以做到:

SELECT sum(revenue) as revenue
FROM employee_rev r
WHERE 123 in (r.employee_id, r.manager_id);

也就是说,对于给定的ID,请在两列中查找。员工永远都不会出现在经理栏中,因此这似乎可以完成您想要的事情。

编辑:

对于多个ID,您将必须进行独立测试。要么:

WHERE 123 IN (r.employee_id, r.manager_id) OR
      456 IN (r.employee_id, r.manager_id)

或:

WHERE r.employee_id in (123, 456) OR
      r.manager_id in (123, 456)

答案 1 :(得分:0)

使用并集将两个选择添加到一个“表”中,然后对其求和。我认为这应该有效

SELECT sum(result) from (
    SELECT      
       sum(revenue) as result
    FROM 
       employee_rev r
    WHERE
       r.manager_id in ('123')
    UNION ALL 
    SELECT      
        sum(revenue) as result
    FROM 
        employee_rev r
    WHERE
        r.employee_id in ('124')