mysql - 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
解决方案
如果一个人的分数在两年之间上升,则自行加入表格:
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
查看演示
推荐阅读
- php - Warning: sqlsrv_fetch_array() expects parameter 1 to be resource when using explode() as variable in multiple SQL query | PHP, SQL
- python - 如何制作一个向文件添加数字并再次加载自身数字+1的函数?
- matlab - 如何修复“方法解析错误:用法可能是无效的 MATLAB 语法。?
- android - Room:如何将 SQLite 方法转换为 Dao 的 @Query
- javascript - Javascript按值在多维数组中搜索?
- php - 如何检查 API 资源中是否存在字段?
- azure-cognitive-search - 扩展操作期间的可用性
- amazon-s3 - 如何在 Spark-SQL 中收集 AWS Glue(目录)表的统计信息
- swift - 无法弄清楚如何从 Firestore 获取复杂的数组
- vue.js - 获取 v-textarea 中的选定文本