How to formulate a SQL Server indexed view that aggregates distinct values?
Posted
by Jeremy Lew
on Stack Overflow
See other posts from Stack Overflow
or by Jeremy Lew
Published on 2010-04-28T18:41:43Z
Indexed on
2010/04/28
18:47 UTC
Read the original article
Hit count: 335
I have a schema that includes tables like the following (pseudo schema):
TABLE ItemCollection {
ItemCollectionId
...etc...
}
TABLE Item {
ItemId,
ItemCollectionId,
ContributorId
}
I need to aggregate the number of distinct contributors per ItemCollectionId. This is possible with a query like:
SELECT ItemCollectionId, COUNT(DISTINCT ContributorId) FROM Item
GROUP BY ItemCollectionId
I further want to pre-calculate this aggregation using an indexed (materialized) view. The DISTINCT prevents an index being placed on this view. Is there any way to reformulate this which will not violate SQL Server's indexed view constraints?
© Stack Overflow or respective owner