返回非顺序记录

时间:2013-10-23 15:12:26

标签: sql sql-server tsql sql-server-2008-r2

我有一个显示已过滤记录的网格视图,也就是说,主键ID中存在间隙。

过滤器通常应用于3列:

dev_ID (nvarchar)
date
code_ID (nvarchar)

和随机的第4列,在下一个查询中不会被过滤。

选择gridview记录时,

我想返回DB并获取所选gridview记录之前和之后的10条记录

(我可以从这个实例中的PK开始)。

这些记录可能仍会NOT在主键ID上依次排列,并基于其他因素,

之前可能没有10条记录,之后可能没有10条记录。

新查询应返回所选记录之前和之后的10条记录,

其中dev_ID = @x,code_Id = @y和date = @someDate。

电流:

我能够返回两个单独查询中所需的结果,但无法将它们合并为一个结果集。

( SELECT TOP 10
            tblData.*
  FROM      tblData
  WHERE     pk <= 5481
        AND dev_ID = 'REC1'
        AND code_ID = 'FMU'
        AND CAST(event_date_time AS DATE) = '10/18/2013'
  ORDER BY  pk DESC
)
UNION
( SELECT TOP 10
            tblData.*
   FROM      tblData
  WHERE     pk >= 5481
            AND dev_ID = 'REC1'
            AND code_ID = 'FMU'
            AND CAST(event_date_time AS DATE) = '10/18/2013'
  ORDER BY  pk ASC
)

真的可以在这方面使用一些帮助。感谢

更新:

我已采用这种方法并可以使用一些帮助......

WITH NumberedMyTable AS
(
SELECT ROW_NUMBER() OVER (ORDER BY PK) AS RowNumber, *
FROM
    tblData
WHERE dev_ID = 'REC1' AND code_ID = 'FMC' AND CAST(date_time as DATE) = '10/18/2013'
)
SELECT *  
FROM
    NumberedMyTable
WHERE
    ((**SELECT RowNumber FROM NumberedMyTable WHERE PK = 5481)** BETWEEN RowNumber + 10 AND   RowNumber - 10) 

这绝对没有返回任何记录。

如何查询RowNumber

用于在WHERE子句中返回所需范围,BOLDED部分?

原创力量:

WITH    recs
      AS ( SELECT TOP 1
                    *
           FROM     tblData
           WHERE    pk = GDV_PK
           ORDER BY pk
         ),
    r AS ( SELECT TOP 10
                    tblData.*
           FROM     tblData
           WHERE    dev_ID = @x
                    AND code_ID = @y
           ORDER BY PK DESC
         )
SELECT TOP 10
        *
FROM    tblData
WHERE   dev_ID = ( SELECT   dev_ID
                   FROM     r
                 )
        AND CAST(date_time AS DATE) = @someDate
ORDER BY pk

2 个答案:

答案 0 :(得分:0)

SELECT  TOP 10 tblData.*
    FROM    tblData
    WHERE   dev_ID = @x AND code_ID = @y and date = @someDate
    ORDER BY PK DESC
union 
SELECT  TOP 10 tblData.*
    FROM    tblData
    WHERE   dev_ID = @x AND code_ID = @y and date = @someDate
    ORDER BY PK ASC

答案 1 :(得分:0)

我终于制作了一个有效的解决方案,在这里发布给其他可能会出现这种情况的人....

Select * From
(SELECT TOP 10 tblData.*
FROM    tblData
WHERE   pk <= 5481 AND dev_ID = 'REC1' AND code_ID = 'FMU' AND
    CAST(event_date_time as DATE) = '10/18/2013'
UNION
SELECT  TOP 10 tblData.*
FROM    tblData
WHERE   pk >= 5481 AND dev_ID = 'REC1' AND code_ID = 'FMU' AND
    CAST(event_date_time as DATE) = '10/18/2013') A
ORDER BY pk ASC