I have 2 tables (it is only part of table columns that are needed for this query):
Items: Id int, OwnerId int
ItemsRelations: RelationId int, ItemId Int (FK Items(Id))
For each OwnerId i need to calculate result of ratio function: Count of user elements that have links to ItemsRelationstable / count of all user elements.
I wrote this query, but it is slow and not optimal. Is there easier and faster method to do that?
SELECT OwnerId , (100 * SUM(HasRelation))/COUNT(Id) AS Ratio
FROM (
SELECT
oi.OwnerId,
oi.Id,
(CASE WHEN SUM(ir.Id) > 0 THEN 1 ELSE 0 END) HasRelation
FROM Items AS oi
LEFT JOIN ItemsRelations AS ir ON ir.ItemId = oi.Id
GROUP BY oi.Id, oi.OwnerId) tempTab
GROUP BY OwnerId