简体   繁体   中英

MS SQL: Filter datastream to first value every 15 minutes

I would like to apply a filter to filter the data to 15 minutes, with only 1 row for every 15 minutes returned.

I have 2 tables data, each table contains 2 columns: "Tijd" as timestamp, "Kanaal 1" as float. A new row is added to both tables based on the frequency of the program (Table 1) or a external trigger (Table 2).

My current code works on the first table

select [Tijd], [Kanaal 1] 
FROM Table_Metingen 
WHERE datepart(mi,tijd) % 15 = 0

Table 1: (regulary updated)

Tijd                | Kanaal 1
2016-06-27 00:00:00 | 53
2016-06-27 00:01:00 | 53
2016-06-27 00:02:00 | 53
2016-06-27 00:03:00 | 53
2016-06-27 00:04:00 | 53
2016-06-27 00:05:00 | 53
2016-06-27 00:06:00 | 53
2016-06-27 00:07:00 | 53

Tabel 2: (updated by an external trigger)

Tijd                | Kanaal 1
2016-06-27 00:00:01 | 53
2016-06-27 00:01:02 | 53
2016-06-27 00:01:04 | 53
2016-06-27 00:01:10 | 53
2016-06-27 00:02:04 | 53
2016-06-27 00:05:03 | 53
2016-06-27 00:06:02 | 53
2016-06-27 00:10:01 | 53

Output of current code would be as following: Table 1: (regulary updated)

Tijd                | Kanaal 1
2016-06-27 00:00:00 | 53
2016-06-27 00:15:00 | 53
2016-06-27 00:30:00 | 53
2016-06-27 00:45:00 | 53
2016-06-27 01:00:00 | 53
2016-06-27 01:15:00 | 53
2016-06-27 01:30:00 | 53
2016-06-27 01:45:00 | 53

Tabel 2: (updated by an external trigger)

Tijd                | Kanaal 1
2016-06-27 00:00:01 | 53
2016-06-27 00:15:02 | 53
2016-06-27 00:30:04 | 53
2016-06-27 00:45:00 | 53
2016-06-27 00:45:2  | 53 < Extra row, not needed
2016-06-27 01:00:01 | 53
2016-06-27 01:15:03 | 53
2016-06-27 01:30:01 | 53
2016-06-27 01:30:05 | 53 < Extra row, not needed
2016-06-27 01:45:02 | 53

The additional rows are due to the seconds in your Tijd column. 01:30:01 and 01:30:05 both fullfill the check minutes%15 = 0. So either you get rid of the seconds in your query or you use a cte with a row_number() and only select all rows with "rownum = 1" (as example).

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