针对视图优化“最近一个月”查询

时间:2018-10-03 18:04:27

标签: sql sql-server join sql-view

我目前正在使用一个联接查询来构建一个视图,该视图仅返回最近一个月内创建的那些记录,如下所示:

CREATE VIEW [dbo].[MostRecentMonth] AS
SELECT <fields>
FROM dbo.CensusFile
INNER JOIN (
    SELECT MAX(CENSUS_MONTH) as MAXMONTH FROM dbo.CensusFile
)
AS child ON (dbo.CensusFile.CENSUS_MONTH = child.MAXMONTH)
GO

该查询返回的是我期望的结果,但它正在寻找一种构建查询的最佳方法,以便在大型数据集上更高效地运行。任何建议表示赞赏。

1 个答案:

答案 0 :(得分:1)

出于可读性考虑,我将标准移到它所属的WHERE子句中:

CREATE VIEW dbo.MostRecentMonth AS
SELECT <fields>
FROM dbo.CensusFile
WHERE census_month = (SELECT MAX(census_month) FROM dbo.CensusFile);

另一个选择是窗口函数,但我认为它不会更快并且可读性更差。

CREATE VIEW dbo.MostRecentMonth AS
SELECT <fields>
FROM
(
  SELECT <fields>, MAX(census_month) OVER () AS maxmonth
  FROM dbo.CensusFile
) with_maxmonth
WHERE census_month = maxmonth;

对于任一查询而言,最重要的是您在census_month上有一个索引:

CREATE INDEX idx ON MostRecentMonth(census_month);