gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:55:37 26 4
gpt4 key购买 nike

我有下表,其中包含特定部门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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com