Cannot create indexed view because I am referencing a derived table

I am doing a nested SELECT to create a derived table hourly

that gets hourly averages based on feature availability. Using hourly

, I am averaging all of these values ​​to get the daily average, and I want to create an indexed view of the daily average. My request looks like this:

CREATE VIEW DailyView WITH SCHEMABINDING AS
SELECT hourly.Feature,
       AVG(hourly.AvgAvailability) AS AvgAvailability,
       CAST(hourly.DateTime AS date) AS Date FROM
       (SELECT DISTINCT 
                        SC.Feature,  
                        AVG(SA.Availability) AS AvgAvailability, 
                        SA.DateAndHour AS DateTime
       FROM   dbo.ServiceAvailability AS SA LEFT OUTER JOIN
              dbo.ServiceCatalog AS SC ON SA.ServiceID = SC.ServiceID
GROUP BY SC.Feature, SA.DateAndHour) hourly
GROUP BY hourly.Feature, CAST(hourly.DateTime AS date)
GO
CREATE UNIQUE CLUSTERED INDEX IDX_V1 ON DailyView(Date)
GO

      

However, I am unable to create an indexed view this way as I get the following error:

The index cannot be created on the "Reporting.dbo.DailyView" because it refers to the "hourly" view (defined by the SELECT statement in the FROM clause). Try removing the reference to the derived table or not indexing the view.

Indexing this view is important to me since we will be dealing with large amounts of data, but I'm not sure how to get the nested average without the derived table.

+3


source to share


1 answer


The problem isn't just with the subquery. You cannot use AVG in an indexed view. Use SUM and COUNT_Big instead, so when you ask for that view, you can calculate the average. LEFT CONNECTIONS are not allowed. INNER JOINs only



You can check if you can create an indexed view for a derived table after making changes in combination with null indices.

+1


source







All Articles