开发者

How to formulate a SQL Server indexed view that aggregates distinct values?

开发者 https://www.devze.com 2022-12-28 17:54 出处:网络
I have a schema that includes tables like the following (pseudo schema): TABLE ItemCollection { ItemCollectionId

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
开发者_Go百科

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?


Not possible, apparently.


SELECT
   ItemCollectionId,
   COUNT(DISTINCT ContributorId),
   COUNT_BIG(*) AS DummyColumn
FROM Item
GROUP BY ItemCollectionId

An aggregate will require COUNT_BIG(*) as mentioned in MSDN.

This also says "no DISTINCT" and I'm not sure (never tried it, sorry) if this applies to it's use in an aggregate (as you have), or SELECT DISTINCT...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号