SQL Server:从每秒选择行

时间:2016-02-06 17:49:47

标签: sql sql-server sql-server-2012

我有一张桌子,每隔5或3秒插入有关GPS点的信息

例如:

id  timestamp
1   2016-02-06 19:33:02  
2   2016-02-07 19:33:07  
3   2016-02-08 19:33:10  
4   2016-02-09 19:33:15  
5   2016-02-10 19:33:20  
6   2016-02-11 19:33:23  
7   2016-02-12 19:33:27  
8   2016-02-13 19:33:32  
9   2016-02-14 19:33:37  
10  2016-02-15 19:33:40  
11  2016-02-16 19:33:45  
12  2016-02-17 19:33:48  
13  2016-02-18 19:33:53  
14  2016-02-19 19:33:56  
15  2016-02-19 19:34:01  
16  2016-02-19 19:34:05  
17  2016-02-19 19:34:08  
18  2016-02-19 19:34:11  
19  2016-02-19 19:34:16  
20  2016-02-19 19:34:21  
21  2016-02-19 19:34:24  
22  2016-02-19 19:34:29  
23  2016-02-19 19:34:34  
24  2016-02-19 19:34:37      

我希望每30秒获取一次信息。

结果应该是这样的:

id  timestamp
1   2016-02-06 19:33:02  
8   2016-02-13 19:33:32  
15  2016-02-19 19:34:01  
23  2016-02-19 19:34:34         

1 个答案:

答案 0 :(得分:3)

您可以使用分组来获取每30秒间隔的第一个id值:

SELECT t1.id, t1.timestamp
FROM mytable AS t1
INNER JOIN (
  SELECT MIN(id) AS id      
  FROM mytable
  GROUP BY CAST(timestamp AS DATE),
           DATEPART(hh, timestamp),
           DATEPART(mi, timestamp),         
           DATEPART(s, timestamp) / 30
) AS t2 ON t1.id = t2.id

Demo here