mysql查询连续3个月以上_MySQL查询显示连续的结果
#mysql中 對(duì)于查詢結(jié)果只顯示n條連續(xù)行的問(wèn)題#
在領(lǐng)扣上碰到的一個(gè)題目:求滿足條件的連續(xù)3行結(jié)果的顯示
x city built a new stadium, each day many people visit it and the stats are saved as these columns: id, date, people;
please write a query to display the records which have 3 or more consecutive rows and the amount of people more than 100(inclusive).
for example, the table stadium:
+------+------------+-----------+
| id | date | people |
+------+------------+-----------+
| 1 | 2017-01-01 | 10 |
| 2 | 2017-01-02 | 109 |
| 3 | 2017-01-03 | 150 |
| 4 | 2017-01-04 | 99 |
| 5 | 2017-01-05 | 145 |
| 6 | 2017-01-06 | 1455 |
| 7 | 2017-01-07 | 199 |
| 8 | 2017-01-08 | 188 |
+------+------------+-----------+
for the sample data above, the output is:
+------+------------+-----------+
| id | date | people |
+------+------------+-----------+
| 5 | 2017-01-05 | 145 |
| 6 | 2017-01-06 | 1455 |
| 7 | 2017-01-07 | 199 |
| 8 | 2017-01-08 | 188 |
+------+------------+-----------+
1.首先先進(jìn)行結(jié)果集的查詢
select id,date,people from stadium where people>=100;
2.給查詢的結(jié)果集增加一個(gè)自增列
select @newid:=@newid+1 as newid,test.*
from(select @newid:=0)r, test where people>100
3.自增列和id的差值 相同即連續(xù)
select @newid:=@newid+1 as newid,test.* ,@cha:=id-@newid as cha
from(select @newid:=0)r, test where people>100
4.將相同的差值 放在同一張表中,并取出連續(xù)數(shù)量大于3的
select if(count(id)>=3,count_concat(id),null)e from(
select @newid:=@newid+1 as newid,test.* ,@cha:=id-@newid as cha
from(select @newid:=0)r, test where people>100)
as d group by cha
5.將上步得到的表和主表 取得所需要的
select id,date,people from test,
(select if (count(id)>3,group_concat(id),null)e
from (select @newid:=@newid+1 as newid,test.* ,@cha:=id-@newid as cha
from(select @newid:=0)r, test where people>100)as d group by cha ) as f
where f.e is not null and find_in_set(id,f.e);
聽(tīng)說(shuō)還可以用存儲(chǔ)過(guò)程來(lái)完成,不過(guò)我沒(méi)嘗試,稍后嘗試
以上
如您對(duì)本文有疑問(wèn)或者有任何想說(shuō)的,請(qǐng)點(diǎn)擊進(jìn)行留言回復(fù),萬(wàn)千網(wǎng)友為您解惑!
總結(jié)
以上是生活随笔為你收集整理的mysql查询连续3个月以上_MySQL查询显示连续的结果的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 字符串截取后两位,字符串转成数组,再转换
- 下一篇: sql2008能否打开mysql数据库_