mysql - SQL,合并同一个表的两个聚合

标签 mysql sql oracle stored-procedures aggregate

我有下表,其中包含特定部门operator在特定日期针对每个执行的操作数量>目标类型sum1sum2 是特定日期操作 1 和操作 2 的数量,相关操作的解释由 operation_type 列指示.

statistic_id | department | operator | operation_type | target_type | sum1 | sum2 | date |

我将查询该表以收集按 operator 分组的特定时间段内 department 1operation_type 1 统计信息>操作类型如下

SELECT operator, target_type, SUM(sum1) AS op1, SUM(sum2) AS op2 FROM statistics
WHERE
  department = 1 AND
  operation_type = 1 AND
  (date BETWEEN in_start_date AND in_end_date)
GROUP BY operator, target_type
ORDER BY operator, target_type;

此外,我还会查询表以收集同一部门和按相同条件分组的时间间隔的 operation_type 2 的统计信息

SELECT operator, target_type, SUM(sum1) AS op3, SUM(sum2) AS op4 FROM statistics
WHERE
  department = 1 AND
  operation_type = 2 AND
  (date BETWEEN in_start_date AND in_end_date)
GROUP BY operator, target_type
ORDER BY operator, target_type;

我想合并查询结果,这样我会得到像这样的结果

operator | target_type | op1 | op2 | op3 | op4

如何根据一些常见和不同的标准聚合不同的列,同时按同一组列进行分组,从而将表与自身连接起来?

最佳答案

在求和中使用条件聚合:

SELECT operator,
       target_type,
       SUM(CASE WHEN operation_type = 1 THEN sum1 ELSE 0 END) AS op1,
       SUM(CASE WHEN operation_type = 1 THEN sum2 ELSE 0 END) AS op2,
       SUM(CASE WHEN operation_type = 2 THEN sum1 ELSE 0 END) AS op3,
       SUM(CASE WHEN operation_type = 2 THEN sum2 ELSE 0 END) AS op4
FROM statistics
WHERE department = 1 AND
      date BETWEEN in_start_date AND in_end_date
GROUP BY operator, target_type
ORDER BY operator, target_type

这会对整个表进行一次遍历,并根据 operation_type1 还是 2 有条件地获取您想要的总和。请注意,CASE 表达式仅包含 operation_type,而不包含部门或日期。这样做的原因是因为您最初的两个查询共享相同的 WHERE 条件,因此我们不需要移动它们。

关于mysql - SQL,合并同一个表的两个聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43084625/

相关文章:

.net - ORA-21700 : object does not exist or is marked for delete for Associative Array as input parameter called from ODP. 网络

mysql - Node : Getting the values from the result of a multiple statement MySQL query

mysql - 在 on 之后加入 Select 语句

mysql查询左连接和过滤

c# - 从文本框中获取特定值到 GridView ?

java - 指定 jre 绝对路径时 Oracle setup.exe 空间敏感度

sql - Oracle SQL -- 查找不在表中的值

mysql - 如何从用户表中获取选民姓名?

mysql - 如何根据数据计数按月和年进行分组

php - 带有类别的棘手的mysql查询