编写此查询的有效方法

时间:2014-10-16 03:47:19

标签: sql sql-server tsql sql-server-2012

我正在尝试按3列排序记录,然后选择一个特定的ID和之前的记录加上之后的行。这是我的疑问:

;With Cte As
(
    SELECT ROW_NUMBER() Over(Order By Book, PageINT, [IDAuto]) as RowNum,  [IdAuto]

      FROM CCWiseInstr2
)
Select * From Cte
    Where RowNum = (Select RowNum From Cte
    Where IdAuto = 211079)
        UNION
Select * From Cte
    Where RowNum = (Select RowNum - 1 From Cte
    Where IdAuto = 211079)
    UNION
Select * From Cte
    Where RowNum = (Select RowNum + 1 From Cte
    Where IdAuto = 211079)

编写此查询的另一种有效方法是什么?在创建了对我来说看起来有点高的所有索引之后,查询大约需要336 ms

以下是查询的计划:

http://gyazo.com/9a7f1c37d4433665d0949acf03c4561c

感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

您可以在SQL Server中使用LEAD和LAG函数。这是一篇关于Simple Talk的精彩文章,涵盖了所有选项。 (以下代码未经测试)

https://www.simple-talk.com/sql/t-sql-programming/sql-server-2012-window-function-basics/

SELECT
  [IdAuto],
  LAG([IDAuto], 1) OVER(Order By Book, PageINT, [IDAuto]) AS PreviousSale,
  LEAD([IDAuto], 1) OVER(Order By Book, PageINT, [IDAuto]) AS NextSale
FROM
  CCWiseInstr2
WHERE [IdAuto] = 211079;

答案 1 :(得分:2)

这个查询怎么样:

;With Cte As
(
    SELECT ROW_NUMBER() Over(Order By Book, PageINT, [IDAuto]) as RowNum,  [IdAuto]       
        FROM CCWiseInstr2
)
Select RowNum, IDAuto From Cte
    Where RowNum IN ( 
        Select RowNumber  From 
            (
                Select  RowNum - 1 as RowNumPrev, 
                        RowNum as RowNum, 
                        RowNum + 1 as RowNumNext 
                        From Cte
                            Where IdAuto = 211079 
            ) vw unpivot ( 
                            RowNumber For 
                                    IdAuto IN (RowNumPrev, RowNum, RowNumNext ) 
                         ) unpw )

而不是UNION只使用UNPIVOT,它会将您的列转换为您可以在IN中使用的行。让我知道它是怎么回事。