sql查询根据给定的时间范围选择组内的第一个匹配项

时间:2012-12-14 20:52:38

标签: sql tsql

  

可能重复:
  How to group time by hour or by 10 minutes

使用MSSQL获得此结果:

enter image description here

来自以下查询:

SELECT [DATESTAMP],[ZONE],[ALARM] 
FROM [UNIT].[dbo].[LOG] 
WHERE [DATESTAMP] BETWEEN @StartDate AND @EndDate 
    AND [ALARM] ='ERROR' 
    AND [ZONE] IN ('BOX 11','BOX 12') 
ORDER BY DATESTAMP DESC

如何更改查询以仅获取行2,5,9,13,17,19,20?

含义我只希望组内的第一(最旧)行跨越约1分钟。在这个群体中, 而不会出现超过15分钟的错误 问候, Freewheelin

2 个答案:

答案 0 :(得分:0)

如果我理解你,你想要每个特定时刻的最早入场,对吧?如果是这样,试试这个:

SELECT
    DateStamp,
    ZONE,
    Alarm
FROM
    [UNIT].[dbo].[LOG]  
    JOIN 
    (   SELECT 
            DateMinute = DATEADD(second, -DATEPART(second, DateStamp), DateStamp),
            Earliest = MIN(DateStamp)
        FROM
            [UNIT].[dbo].[LOG]  
        GROUP BY
            DATEADD(second, -DATEPART(second, DateStamp), DateStamp)
    ) X ON [UNIT].[dbo].[LOG].DateStamp = X.Earliest

答案 1 :(得分:0)

结束于:

SELECT  MIN([DATESTAMP]) as FirstOccurance FROM ....
WHERE ....
....
GROUP BY DATEPART(minute, [DATESTAMP])
ORDER BY FirstOccurance DESC

- 再次谢谢你们