2017-03-19 66 views
-3

此查詢爲我提供1小時內從1到20的事件值,如果連續的事件值> = 200,如何增加該值?SQL Server查詢下一行值,其中前一行的值爲

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,而不是哪個小時。 請原諒我,我仍然生疏與崗位格式化!

+0

檢查您的示例表。似乎錯了 –

+0

你到目前爲止嘗試過什麼 - 請顯示你當前的代碼。 –

+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) 
; 
+0

你試過我的例子嗎? –

+0

對不起,我忘記了你的問題的「一小時內」部分。你可以再試一次嗎? –

+0

你可以用示例數據設置一個rextester演示來說明問題嗎? –

相關問題