0

我有一条 SQL 语句,我目前正在使用它从数据库中返回多行:

SELECT
    as1.AssetTagID, as1.TagID, as1.CategoryID,
    as1.Description, as1.HomeLocationID, as1.ParentAssetTagID
FROM Assets AS as1
    INNER JOIN AssetsReads AS ar  ON as1.AssetTagID = ar.AssetTagID
WHERE
    (ar.ReadPointLocationID='Readpoint1' OR ar.ReadPointLocationID='Readpoint2')
    AND (ar.DateScanned between 'LastScan' AND 'Now')
    AND as1.TagID!='000000000000000000000000'

我想做一个查询,DateScanned该查询将从该查询中获取最旧的行,并从数据库中获取另一行,如果在该行的某个时间段内有一行(例如 5 秒)。通过按降序选择第一个记录,最旧的记录会相对简单,但是如果第二个记录在第一个记录的某个时间段内,我如何获得第二个记录?

我知道我可以用多个查询来完成这个过程,但是有没有办法将这个过程组合成一个查询?

我使用的数据库是 SQL Server 2008 R2。

另请注意,DateScanned时间只是占位符,我正在使用此查询的应用程序中处理它。

4

2 回答 2

1

这是一个相当普遍的方法来处理它。使用窗口函数获取最早的扫描日期min(),然后使用日期算术获取您想要的任何行:

select t.*  -- or whatever fields you want
from (SELECT as1.AssetTagID, as1.TagID, as1.CategoryID,
             as1.Description, as1.HomeLocationID, as1.ParentAssetTagID,
             min(DateScanned) over () as minDateScanned, DateScanned
      FROM Assets AS as1
           INNER JOIN AssetsReads AS ar  ON as1.AssetTagID = ar.AssetTagID
      WHERE (ar.ReadPointLocationID='Readpoint1' OR ar.ReadPointLocationID='Readpoint2')
            AND (ar.DateScanned between 'LastScan' AND 'Now')
            AND as1.TagID!='000000000000000000000000'
     ) t
where datediff(second, minDateScanned, DateScanned) <= 5;
于 2013-08-09T20:21:04.983 回答
1

我不太确定sql server语法,但你可以做这样的事情

SELECT * FROM (
  SELECT 
    TOP 2
    as1.AssetTagID, 
    as1.TagID, 
    as1.CategoryID, 
    as1.Description, 
    as1.HomeLocationID, 
    as1.ParentAssetTagID ,
    ar.DateScanned,
    LAG(ar.DateScanned) OVER (order by ar.DateScanned desc) AS lagging
  FROM 
    Assets AS as1
    INNER JOIN AssetsReads AS ar
      ON as1.AssetTagID = ar.AssetTagID
  WHERE (ar.ReadPointLocationID='Readpoint1' OR ar.ReadPointLocationID='Readpoint2')
    AND (ar.DateScanned between 'LastScan' AND 'Now')
    AND as1.TagID!='000000000000000000000000'
  ORDER BY
    ar.DateScanned DESC  
)
WHERE 
  lagging IS NULL or DateScanned - lagging < '5 SECONDS'

我试图对结果进行排序DateScanned desc,然后只对最上面的 2 行进行排序。然后,我使用lag()DateScanned 字段上的函数来获取DateScanned上一行的值。对于最上面的行DateScanned,其第一条记录应为空,但对于第二条记录,它应为第一行的值。然后,您可以比较这两个值以确定是否要显示第二行

有关滞后功能的更多信息:http: //blog.sqlauthority.com/2011/11/15/sql-server-introduction-to-lead-and-lag-analytic-functions-introduced-in-sql-server-2012 /

于 2013-08-09T19:14:40.873 回答