我已经在SQL Server中创建了以下视图。它在视图中使用了两组ROW_NUMBER OVER PARTITION
查询,因为两个引用的表在ServerName
日期/时间范围内将多次出现相同的RowInsertDateTime
,而我只是感兴趣在每个表的最新行中。
返回471行需要4秒钟。这些表都不包含索引。我希望获得一些帮助,以了解我可以添加哪些索引来改善视图的性能。我已经检查了实际的执行计划,两种查询分别占总查询成本的11%和35%。
视图定义:
CREATE VIEW ViewInSiteSuperTable
AS
SELECT
sales.ServerName,
GETDATE() AS RowInsertDateTime,
sales.daily_sales,
basket.AvgBasketAmount,
basket.AvgBasketQty,
oos.OutOfStockCount,
tph.transactions_per_hour,
tph.total_transactions
FROM
dbo.InSiteEodSalesPerDayPerStore sales WITH (NOLOCK)
INNER JOIN
(SELECT
ServerName,
RowInsertDateTime,
AvgBasketAmount,
AvgBasketQty
FROM
(SELECT
ServerName,
RowInsertDateTime,
AvgBasketAmount,
AvgBasketQty,
ROW_NUMBER() OVER (PARTITION BY ServerName ORDER BY RowInsertDateTime DESC) rn
FROM
InSiteAvgBasketSize) q
WHERE
rn = 1) basket ON basket.ServerName = sales.ServeRName
INNER JOIN
(SELECT
ServerName,
RowInsertDateTime,
transactions_per_hour,
total_transactions
FROM
(SELECT
ServerName,
RowInsertDateTime,
transactions_per_hour,
total_transactions,
ROW_NUMBER() OVER (PARTITION BY ServerName ORDER BY RowInsertDateTime DESC) rn
FROM
InSiteTxPerHourPerDayTotals) q
WHERE
rn = 1) tph ON tph.ServerName = sales.ServerName
INNER JOIN
dbo.InSiteOutOfStocksAllStores oos WITH (NOLOCK) ON oos.ServerName = sales.ServerName
WHERE
sales.daily_sales_date = DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)
执行计划
答案 0 :(得分:1)
消除2个sotrs的指标是:
create index ix_ServerName_RowInsertDateTime on InSiteTxPerHourPerDayTotals
(ServerName asc, RowInsertDateTime desc) include(transactions_per_hour, total_transactions)
create index ix_ServerName_RowInsertDateTime on InSiteAvgBasketSize
(ServerName asc, RowInsertDateTime desc) include(AvgBasketAmount, AvgBasketQty)
但是,您应该在问题中加入actual execution plan
,而不是图片,而要使用Paste The Plan
我了解基本索引,例如用于删除表扫描的基本索引,但是 非常想了解这些索引背后的想法 建议。
在这种情况下,索引不是删除scan
,而是删除sort
。无论如何,这两个表都会被扫描,您想枚举所有行,因此您无法删除scan
,但是想在每个ServerName
组中枚举,它是第一个index key
,并且您想按每个组中的RowInsertDateTime
进行排序,因此它是第二个index key
。这两个字段在订购时已经具有所需的内容:它们在s组中按顺序排列。
其他字段为included
,因为它们不需要按顺序排列,但没有它们,则查询的索引不是covering
,即服务器将对基表进行查找以获取它们,因为它们是select
子句中显示。