从列表中获取第一行查询

时间:2017-03-01 22:06:01

标签: sql partition

我有一张包含许多标签的表,其中包含时间序列数据 例如:

TagName  Value  DateTime              Quality
Tag1      75    09/24/2015 01:05:10    192 
Tag1      76.5  09/24/2015 01:05:20    192 
Tag1      75    09/24/2015 01:05:40    192 
Tag1      74.5  09/24/2015 01:06:00    192 
Tag2      75    09/24/2015 01:05:10    192
Tag2      76.5  09/24/2015 01:05:20    192 
Tag2      75    09/24/2015 01:05:40    192 
Tag2      74.5  09/24/2015 01:06:00    192

我需要查询StartDate和EndDate之间的标签(多个)和间隔(5分钟/ 15分钟)

此查询有效:

SELECT * FROM   
(SELECT [DateAndTime],[TagName],[Val],row_number()over(partition by datepart(minute, [DateAndTime])order by [DateAndTime] ) as "rn"
FROM [FloatTable]   WHERE
([DateAndTime] BETWEEN @StartDateTime AND @EndDateTime) AND 
([TagName] IN (@TagName)) AND
( (DATEPART("n",[DateAndTime]) % @IntervalInMins = 0) )) x
WHERE rn = 1

带参数:

  • 间隔时间:5分钟
  • 标签:' Tag1中'
  • StartDateTime:' 2014-02-26 09:00:00'
  • EndDateTime:' 2014-02-26 11:00:00'

查询结果:

TagName  Value  DateTime              Quality    
Tag1     75    09/24/2015 01:05:10    192     
Tag1     76.5  09/24/2015 01:10:10    192     
Tag1     75    09/24/2015 01:16:40    192

但这只适用于我们一次查询1个标签的情况。通常我们想查询标签列表。如果我查询标签列表' Tag1,Tag2'查询仅提供Tag1的结果。请指教。

1 个答案:

答案 0 :(得分:0)

我认为您只需要将tagname添加到partition by并删除where中的过滤:

SELECT x.*
FROM (SELECT [DateAndTime], [TagName], [Val],
             row_number() over (partition by tagname, datepart(minute, [DateAndTime])
                                order by [DateAndTime]
                               ) as rn
      FROM [FloatTable]
      WHERE ([DateAndTime] BETWEEN @StartDateTime AND @EndDateTime) AND 
            ( (DATEPART("n",[DateAndTime]) % @IntervalInMins = 0) )
     ) x
WHERE rn = 1