按时间选择Top nth group

时间:2012-05-24 20:21:12

标签: sql sql-server-2000

我有这个结果集片段,

DateAndTime         Date        Hr  Min Tag Val
11/15/2011 0:00:29  11/15/2011  0   0   47  0.084000006318092
11/15/2011 0:00:59  11/15/2011  0   0   47  0.086000002920628
11/15/2011 0:00:13  11/15/2011  0   0   47  0.084000006318092
11/15/2011 0:00:44  11/15/2011  0   0   47  0.087000004947186
11/15/2011 0:05:06  11/15/2011  0   5   47  0.088500000536442
11/15/2011 0:05:21  11/15/2011  0   5   47  0.084500007331371
11/15/2011 0:05:51  11/15/2011  0   5   47  0.086000002920628
11/15/2011 0:05:36  11/15/2011  0   5   47  0.088000006973743
11/15/2011 0:10:41  11/15/2011  0   10  47  0.086000002920628
11/15/2011 0:10:56  11/15/2011  0   10  47  0.089500002563000
11/15/2011 0:10:09  11/15/2011  0   10  47  0.086500003933907
11/15/2011 0:10:25  11/15/2011  0   10  47  0.089000001549721
11/15/2011 0:15:45  11/15/2011  0   15  47  0.089000001549721
11/15/2011 0:15:14  11/15/2011  0   15  47  0.087500005960465
11/15/2011 0:15:29  11/15/2011  0   15  47  0.089500002563000
11/15/2011 0:20:48  11/15/2011  0   20  47  0.106000006198883
11/15/2011 0:20:03  11/15/2011  0   20  47  0.109500005841255
11/15/2011 0:20:18  11/15/2011  0   20  47  0.104500003159046
11/15/2011 0:20:33  11/15/2011  0   20  47  0.109000004827976

我只想在0分钟,分钟5分钟,分钟10分钟等单行返回

4 个答案:

答案 0 :(得分:0)

DECLARE @Minutes VARCHAR(1000) 
;WITH MyRecords AS
(
   SELECT TOP 3 Distinct Min FROM TableName
)


SELECT @Minutes = COALESCE(@Minutes + ', ', '') + MINFROM MyRecords 

PRINT @Minutes

结果:0,5,10

如果您需要添加分钟,可以在@Minutes之前轻松添加:)

答案 1 :(得分:0)

SELECT *, 
       id = IDENTITY(INT, 1, 1) 
INTO   #temp 
FROM   MyTable 
ORDER  BY [min] 

SELECT o.* 
FROM   #temp o 
WHERE  o.id = (SELECT Min(id) 
               FROM   #temp t 
               WHERE  t.[Min] = o.[Min]) 

答案 2 :(得分:0)

这是您需要窗口功能的情况,但它们在SQL Server 2000中不可用。

这是另一种选择:

select t.*
from t join
     (select date, hour, min, min(datetime) as mindatetime
      from t
      group by date, hour, min
     ) tsum
     on t.datetime = tsum.mindatetime

这假定datetime字段是唯一的。否则,如果列中有id,则可以使用该ID。

答案 3 :(得分:0)

我相信以下内容适用于所有RDBMS(但是,我目前无法对其进行测试):

SELECT actual.DateAndTime, actual.Tag, actual.Val
FROM ResultTable actual
LEFT JOIN ResultTable exclude
ON exclude.Date = actual.Date
AND exclude.Hr = actual.Hr
AND exclude.Min = actual.Min
AND exclude.DateAndTime > actual.DateAndTime
WHERE exclude.DateAndTime IS NULL

...应该每分钟为您提供“最新”行数。