Mysql 如何在SQL中应用`GROUPBY`查找同一列中的差异?
我需要找到按Mysql 如何在SQL中应用`GROUPBY`查找同一列中的差异?,mysql,sql,Mysql,Sql,我需要找到按Id列分组的点之间的差异 Id | Year | Points ---+------+------- 1 | 2017 | 10 1 | 2018 | 20 2 | 2017 | 13 2 | 2018 | 16 3 | 2017 | 25 3 | 2018 | 20 预期结果: Id | Points ---+------- 1 | 10 2 | 3 3 | -5 如果您想要年份之间的差异,您不需要分组依据: select t2017.id, t2017.po
Id
列分组的点之间的差异
Id | Year | Points
---+------+-------
1 | 2017 | 10
1 | 2018 | 20
2 | 2017 | 13
2 | 2018 | 16
3 | 2017 | 25
3 | 2018 | 20
预期结果:
Id | Points
---+-------
1 | 10
2 | 3
3 | -5
如果您想要年份之间的差异,您不需要
分组依据
:
select t2017.id, t2017.points as points_2017,
t2018.points as points_2018,
(t2018.points - t2017.points) as diff
from t t2017 join
t t2018
on t2017.id = t2018.id and
t2017.year = 2017 and
t2018.year = 2018;
您可以使用条件聚合执行非常类似的操作:
select id,
sum(case when year = 2017 then points end) as points_2017,
sum(case when year = 2018 then points end) as points_2018,
(sum(case when year = 2018 then points end) -
sum(case when year = 2017 then points end)
) as diff
from t
group by id;
PS.需要MySQL 8+。进行聚合
select
id,sum(case when year = 2018 then points end) -sum(case when year = 2017 then points end) as diff
from tablename group by id
分享您的预期结果@Zaynulabadinthin
select
id,sum(case when year = 2018 then points end) -sum(case when year = 2017 then points end) as diff
from tablename group by id