gpt4 book ai didi

Mysql 寻找差异

转载 作者:行者123 更新时间:2023-11-29 19:08:00 26 4
gpt4 key购买 nike

嗨,我有这样的数据

month | type  | passenger |
2 | 1 | 15 |
2 | 2 | 20 |
2 | 2 | 18 |
3 | 2 | 10 |
3 | 1 | 15 |
3 | 1 | 25 |
4 | 2 | 30 |
4 | 1 | 16 |

我想按类型对两个月的乘客进行汇总,并找出两者之间的差异。例如。

SUM(passenger) as month2 where month=2 group by type

SUM((passenger) as month3 where month=3 group by type

这里是第二个月
类型1 = 15
类型2 = 38

第 3 个月
类型1 = 40
类型2 = 10

所以我想要像这样的结果

Difference
type1 = 25
type2 = 28

是否可以在一个查询中完成此操作?

感谢您的帮助和建议。

最佳答案

我将在 sum() 中使用条件语句来仅汇总给定月份的数据,并按类型分组:

select type, abs(sum(if(month=2,passenger,0))-sum(if(month=3,passenger,0))) as difference
from table
where month in (2,3)
group by type

关于Mysql 寻找差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43334573/

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