;WITH x AS ( SELECT ItemID, c = COUNT(*) FROM dbo.ItemViews GROUP BY ItemID ) UPDATE i SET TotalViews = xc FROM dbo.Items AS i INNER JOIN x ON x.ItemID = i.ItemID;
But why do you want to keep this value when you can always get an invoice at runtime? You will have to run this update statement every time you touch the ItemViews table in any way, otherwise the account stored with the items will be incorrect.
Instead, you can create an indexed view:
CREATE VIEW dbo.ItemViewCount WITH SCHEMABINDING AS SELECT ItemID, ItemCount = COUNT_BIG(*) FROM dbo.ItemViews GROUP BY ItemID; GO CREATE UNIQUE CLUSTERED INDEX x ON dbo.ItemViewCount(ItemID);
Now you can join the scan in your queries and know that the invoice is always updated (without paying a fine for scanning to count each item). The disadvantage of an indexed view is that you pay this cost gradually when there is an insert / update / delete in the ItemViews table.
source share