在具有“组的最新记录”选择的视图上创建索引

时间:2018-07-09 12:45:30

标签: sql-server tsql indexed-view

我正在尝试使用索引视图来提高视图的性能,但是我不确定是否可以克服这些限制。

在我看来,我正在尝试为特定组选择最新记录。我可以使用内部选择或使用具有row_number()OVER..PARTITION BY的通用表表达式来编写此类查询。

但是,这两种方法都无法在视图上创建索引。还有其他方法可以编写视图以便在其上创建索引吗?

SELECT [Person ID], [Updated DateTime], Email
FROM   dbo.[People Information History] AS [People Information]
WHERE  ([People Information].[Updated DateTime] =
            (SELECT        MAX([Updated DateTime]) AS Expr1
            FROM            dbo.[People Information History]
            WHERE        ([People Information].[Person ID] = [Person ID])))

WITH [Current  Information]
AS
(
    SELECT [Person ID], [Updated DateTime], Email,
           row_number() OVER (PARTITION BY [Updated DateTime] ORDER BY [Updated DateTime] DESC) as RowNum
    FROM dbo.[People Information History]
)

SELECT [Person ID], [Updated DateTime], Email
FROM   [Current  Information]
WHERE RowNum = 1

1 个答案:

答案 0 :(得分:0)

您应该在实际表上创建索引。

您的第二个脚本似乎有问题,例如:

PARTITION BY [Person ID]

参考Create Indexed Views