A colleague wrote this piece of SQL (SQL Server 2012):
SELECT
a.account_id
,(SELECT SUM(e.amount)
FROM event e
WHERE e.event_type_id <> 47
AND e.master_comm_id = (SELECT c.comm_id
FROM comm c
WHERE c.item_id = a.item_id
AND c.comp_type_id = 20
AND c.comm_type_id = 485))
FROM account a
However, there are cases where there are multiple master_comm_ids against an event, and so the query fails (Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.). I only want the first master_comm_id, ie. the MIN one.
I have looked at various similar questions and attempted various things to achieve this (using MIN or ROW_NUMBER and rearranging the query to use joins etc) but I must be missing something obvious as everything has either resulted in SQL errors or the wrong data or not fixed the issue.
Can anyone help me just find the min master_comm_id to then use in the subquery?