Search code examples
sqlt-sqlsubqueryindexed-view

Need some help making an Indexed view with 2 COUNT_BIG's


Ok, I'm trying to make an indexed view that is against a simple table that stores the results of what people think is good/bad for a post. This is the results of a thumbs up / thumbs down, voting on posts.

So here's my pseduo fake table :-

HelpfulPostId INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
PostId INT NOT NULL,
IsHelpful BIT NOT NULL,
UserId INT NOT NULL

So a user can only have one vote per post. It's either a 1 (helpful) or 0 (unhelpful) <-- not sure of a better way to handle that, if there is a better way.

Ok. What i'm trying to do is get a view that looks like the following.

HelpfulPostId INT IDENTITY(1,1) NOT NULL PRIMARY KEY,

PostId INT NOT NULL,
IsHelpfulCount COUNT_BIG (WHERE IsHelpful = 1)
IsNotHelpfulCount COUNT_BIG (WHERE IsHelpful = 0)

And finally, i'll need to make it schemabindable so i can add an index on the PK and then an index on the PostId.

I have no idea about the sql to make the view. Any suggestions?

Cheers :)


Solution

  • Thoughts:

    • You can't use COUNT(*) in an indexed view
    • You can't aggregate bit fields

    There are other limitations of indexed views

    CREATE VIEW dbo.Example
    WITH SCHEMABINDING
    AS
    SELECT
        PostId,
        SUM(CAST(IsHelpful AS bigint)) AS IsHelpfulCount,
        SUM(CAST(1-IsHelpful AS bigint)) AS IsNotHelpfulCount,
        COUNT_BIG(*) AS Dummy   --Used to satisfy requirement
    FROM
        dbo.bob
    GROUP BY
        PostId
    GO
    CREATE UNIQUE CLUSTERED INDEX IXC_Test ON dbo.Example (PostId)
    GO
    

    Edit: Removed the Identity field, which was accidently added to the original question/post.

    Edit 2 (gbn): I forgot that any aggregate in an indexed view also needs a COUNT_BIG(*). So, simply add one as a dummy column. I've tested this.

    If the view definition uses an aggregate function, the SELECT list must also include COUNT_BIG (*).