Mysql从有5年差距的行中选择年份

时间:2016-12-14 01:10:58

标签: mysql

+------+-------+
| Col1 | Col2  |
+------+-------+
| 0    | 2008  |
| 0    | 2013  |
| 1    | 2014  |
| 1    | 2015  |
| 0    | 2020  |
| 0    | 2021  |
| 0    | 2022  |
+------+-------+

如果我有一个包含上述数据的表结果。使用Mysql,我如何选择年份间隔为5年及以上的年份,其中较低年份的col1等于1? 例如,在2020年返回该行 感谢

2 个答案:

答案 0 :(得分:1)

假设Col2是唯一的:

select min(t2.Col2)
from mytable t1
join mytable t2 on t2.Col2 > t1.Col2
where t1.Col1 = 1
group by t1.Col2
having min(t2.Col2) >= t1.Col2 + 5

sqlfiddle

答案 1 :(得分:0)

从table_name sc1,table_name sc2中选择sc1.col2 其中sc1.col2> sc2.col1 group by sc1.col1 HAVING sc1.col2> = sc1.col1 + 5;