简体   繁体   中英

How to get record for every 2 minutes in SQL

I have a data table that has entries for every one minute, it's bulky dataset. So I need to get every 2 minutes data retrieving 10 minutes dataset from last valid record . All these data is used in the graph drawing, so trying to limit the number of records displayed in the chart. eg for a sample looks like this:

DateTime
2016-01-01  08:22:00
2016-01-01  08:21:00
2016-01-01  08:20:00
2016-01-01  08:19:00
2016-01-01  08:18:00
2016-01-01  08:17:00
2016-01-01  08:16:00
2016-01-01  08:15:00
2016-01-01  08:14:00
2016-01-01  08:13:00
2016-01-01  08:12:00
2016-01-01  08:11:00
2016-01-01  08:10:00

Expected records result:

2016-01-01  08:21:00
2016-01-01  08:19:00
2016-01-01  08:17:00
2016-01-01  08:15:00
2016-01-01  08:13:00

How can I do it in SQL query?

For retrieving the values you can use the following:

SELECT
    *
FROM
    YourTable AS T
WHERE
    T.DateTimeColumn >= DATEADD(MINUTE, -10, GETDATE())

And for your periodical task you can create a SQL Server Agent job that runs the previous query every 2 minutes.

If you are using SQL Server :

  1. You can schedule a job in SQL Server Agent
  2. Write a Loop in SQL and run it. You may alter @end_time calculation for increasing time limit from 10 to something bigger.

     DECLARE @interval int = 2, @start_time datetime , @end_time datetime set @start_time = GETDATE(); set @end_time = DATEADD(M, 10, @start_time) while (@start_time < @end_time) BEGIN select * from [TABLENAME ] where [col] between @start_time and DATEADD(M, @interval, @start_time) set @start_time = DATEADD(M, @interval, @start_time) END 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM