是否可以在索引视图的SELECT语句中执行除法?我添加列结果的那一刻,即一列的值除以另一列,我开始得到以下错误:
无法在视图“MyDB.dbo.getUsageForUsers”上创建聚簇索引“CX_t”,因为视图的选择列表包含聚合函数或分组列结果的表达式。考虑从聚合函数的结果中删除表达式或从选择列表中分组列。
SUM(ISNULL(DATEDIFF(minute, ac.StartTime, ac.EndTime), 0)) AS Effort,
SUM(ISNULL(DATEDIFF(minute, ut.StartTime, ut.EndTime), 0)) AS Availability,
-- Below line leads to the error in the question
SUM(ISNULL(DATEDIFF(minute, ac.StartTime, ac.EndTime), 0)) / SUM(ISNULL(DATEDIFF(minute, ut.StartTime, ut.EndTime), 0)) AS Utilisation,
谢谢
如错误所示,您无法创建与聚合结果一起使用的表达式。但你可以做的是创建两个视图。第一个视图,即索引的视图,只计算聚合(Effort
和Affordability
)。第二个视图,非索引,使用第一个视图,可以执行进一步的计算(Utilisation
),并通过查询代码使用。
您仍然可以从维护聚合的索引中受益,这是索引视图经常被引入的昂贵操作。
CREATE VIEW dbo.V1
WITH SCHEMABINDING
AS
SELECT
SUM(ISNULL(DATEDIFF(minute, ac.StartTime, ac.EndTime), 0)) AS Effort,
SUM(ISNULL(DATEDIFF(minute, ut.StartTime, ut.EndTime), 0)) AS Availability,
...
CREATE INDEX IX_V1 on dbo.V1 (...)
CREATE VIEW dbo.V2
WITH SCHMEBINDING
AS
SELECT
Effort,
Availability,
Effort/Availability as Utilisation
/* Other calcs */
FROM
dbo.V1 WITH (NOEXPAND)