SQL- 601. 体育馆的人流量

项目描述

X 市建了一个新的体育馆,每日人流量信息被记录在这三列信息中:序号 (id)、日期 (date)、 人流量 (people)。

请编写一个查询语句,找出高峰期时段,要求连续三天及以上,并且每天人流量均不少于100。

例如,表 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       |
+------+------------+-----------+

对于上面的示例数据,输出为:

+------+------------+-----------+
| id   | date       | people    |
+------+------------+-----------+
| 5    | 2017-01-05 | 145       |
| 6    | 2017-01-06 | 1455      |
| 7    | 2017-01-07 | 199       |
| 8    | 2017-01-08 | 188       |
+------+------------+-----------+

Note:
每天只有一行记录,日期随着 id 的增加而增加。

SQL Server版:

DECLARE @sid INT;
DECLARE @sdate DATE;
DECLARE @speople INT;
DECLARE @startdate DATE;
DECLARE  @nextdate Date;
DECLARE  @thisN INT =0;
DECLARE my_coursor CURSOR FOR SELECT id,date,people FROM stadium WHERE people >=100
OPEN my_coursor
FETCH NEXT FROM my_coursor INTO @sid ,@sdate,@speople;
SET @startDate=@sdate;
SET @nextDate=@sdate;
WHILE @@FETCH_STATUS=0
BEGIN
IF(@sdate = DATEADD(DAY,1,@nextDate))
BEGIN
    SET @nextDate=@sdate;
    SET @thisN=@thisN+1;
END
ELSE 
BEGIN
    SET @startDate=@sdate;
    SET @nextDate=@sdate;
    SET @thisN=0;
END
FETCH NEXT FROM my_coursor INTO @sid,@sdate,@speople;
END
CLOSE my_coursor;
DEALLOCATE  my_coursor;
IF(@thisN>=3)
BEGIN
    SELECT * FROM dbo.stadium WHERE date>=@startDate AND date <=@nextDate
END

你可能感兴趣的:(SQL- 601. 体育馆的人流量)