简体   繁体   English

SQL每n分钟选择一行

[英]SQL select one row for every n minutes

I'm using Microsoft SQL Server 2008, and have a data set that has entries for every few minutes, over a long period of time. 我正在使用Microsoft SQL Server 2008,并且有一个数据集,该数据集在很长一段时间内每隔几分钟就有条目。 I am using a program to graph the data, so i need to return about 20 values per hour. 我正在使用一个程序来绘制数据图形,所以我需要每小时返回大约20个值。 Some days the data is every minute, sometimes every five minutes, and sometimes every 8 or 9 minutes, so selecting every nth row won't give an even spread over time 有时数据是每分钟,有时是每五分钟,有时是每8或9分钟,因此选择第n行不会在时间上平均分配

eg for a sample in 2012, it looks like this : 例如,2012年的样本看起来像这样:

DateTime
2012-01-01 08:00:10.000
2012-01-01 08:08:35.000
2012-01-01 08:17:01.000
2012-01-01 08:25:26.000

and for a sample the next year it looks like this: 下一年的样本看起来像这样:

DateTime
2013-07-20 08:00:00.000
2013-07-20 08:01:00.000
2013-07-20 08:02:00.000
2013-07-20 08:03:00.000
2013-07-20 08:04:00.000

at the moment I am using a statement like this: 目前,我正在使用这样的语句:

SELECT * FROM [Master]
WHERE (((CAST(DATEPART(hour, DateTime)as varchar(2)))*60)
      +CAST(DATEPART(minute, DateTime)as varchar(2))) % '5' = '0' 

ORDER BY DateTime

This works fine for july 2013, but I miss most points in 2012, as it returns this 这在2013年7月效果很好,但我错过了2012年的大多数要点,因为它返回了

DateTime
2012-01-01 08:00:10.000
2012-01-01 08:25:26.000
2012-01-01 08:50:43.000
2012-01-01 09:15:59.000
2012-01-01 10:40:14.000
2012-01-01 11:05:30.000

What better way is there to do this? 有什么更好的方法可以做到这一点?

EDIT: The table has a DateTime column, and a pressure column, and I need to output both and graph pressure against date and time. 编辑:该表有一个DateTime列,和一个压力列,我需要输出两者,并针对日期和时间绘制压力图。

Since they can be random for the hours, this should work for what you need: 由于它们在几个小时内可能是随机的,因此应该可以满足您的需求:

Declare @NumberPerHour Int = 20

;With Cte As
(
    Select  DateTime, Row_Number() Over (Partition By DateDiff(Hour, 0, DateTime) Order By NewId()) RN
    From    Master
)
Select  DateTime
From    Cte
Where   RN <= @NumberPerHour
Order By DateTime Asc

This will group the rows by the hour, and assign a random Row_Number ID to them, and only pull those with a Row_Number less than the number you're looking for per hour. 这将按小时对行进行分组,并为它们分配一个随机的Row_Number ID,并且仅拉取Row_Number小于您每小时所需数量的行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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