SQL Server查询下一行值的前一行值

时间:2017-03-19 16:10:27

标签: sql-server

此查询在一小时内为我提供1到20的事件值,如果连续的事件值>> 200,如何添加到该值?

SELECT ID, count(Event) as numberoftimes 
FROM table_name
WHERE Event >=1 and Event <=20
GROUP BY ID, DATEPART(HH, AtHour)
HAVING DATEPART(HH, AtHour) <= 1 
ORDER BY ID desc

在这个虚拟的24小时表中:

+----+-------+--------+
| ID | Event | AtHour |
+----+-------+--------+
|  1 |     1 | 11:00  |
|  1 |     4 | 11:01  |
|  1 |     1 | 11:02  |
|  1 |    20 | 11:03  |
|  1 |   200 | 11:04  |
|  1 |     1 | 13:00  |
|  1 |     1 | 13:05  |
|  1 |     2 | 13:06  |
|  1 |   500 | 13:07  |
|  1 |    39 | 13:10  |
|  1 |    50 | 13:11  |
|  1 |     2 | 13:12  |
+----+-------+--------+

我想选择带有事件的ID,范围在1到20之间,然后在一小时内立即显示大于或等于200的值。

预期结果应该是这样的:

+----+--------+
| ID | AtHour |
+----+--------+
|  1 |     11 |
|  1 |     13 |
|  2 |     11 |
|  2 |     14 |
|  3 |     09 |
|  3 |     12 |
+----+--------+

或者仅针对唯一ID而不是几小时发生了多少次。 请原谅我格式化后仍然生锈!

1 个答案:

答案 0 :(得分:0)

CREATE TABLE data (Id INT, Event INT, AtHour SMALLDATETIME);

INSERT data (Id, Event, AtHour) VALUES
(1,1,'2017-03-16 11:00:00'),
(1,4,'2017-03-16 11:01:00'),
(1,1,'2017-03-16 11:02:00'),
(1,20,'2017-03-16 11:03:00'),
(1,200,'2017-03-16 11:04:00'),
(1,1,'2017-03-16 13:00:00'),
(1,1,'2017-03-16 13:05:00'),
(1,2,'2017-03-16 13:06:00'),
(1,500,'2017-03-16 13:07:00'),
(1,39,'2017-03-16 13:10:00')
;

; WITH temp as (
  SELECT rownum = ROW_NUMBER() OVER (PARTITION BY id ORDER BY AtHour)
  , *
  FROM data
)
SELECT a.id, DATEPART(HOUR, a.AtHour) as AtHour, COUNT(*) AS NumOfPairs
FROM temp a JOIN temp b ON a.rownum = b.rownum-1
WHERE a.Event BETWEEN 1 and 20 AND b.Event >= 200 
AND DATEDIFF(MINUTE, a.AtHour, b.AtHour) <= 60
GROUP BY a.id, DATEPART(HOUR, a.AtHour)
;