首页 > 解决方案 > Group By查找SQL中表元素之间的差异?

问题描述

我有一个包含项目索引、分数和年份的表格。我想计算一个人的分数在两年之间上升的每个事件(表格按日期排序),以便下表:

person_index   score   year
3              76      2003
3              86      2004
3              86      2005
3              87      2006
4              55      2005
4              91      2006

我将得到索引为 3 的人员进行 2 次更改的输出,以及人员 4 进行 1 次更改的输出:

person_index   times_changed
3              2
4              1

我正在使用 MySQL 5.7

标签: mysqlsqlgroup-by

解决方案


如果一个人的分数在两年之间上升,则自行加入表格:

select 
  t.person_index,  
  count(*) times_changed
from tablename t
inner join tablename tt
on t.person_index = tt.person_index
and tt.year - t.year = 2
and tt.score > t.score
group by t.person_index

查看演示


推荐阅读