Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何在SQL中应用`GROUPBY`查找同一列中的差异?_Mysql_Sql - Fatal编程技术网

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