Filter customers with negative balance across multiple accounts
This is a very simple query. To get the total balance of each customer (with non-negative total):

SELECT customer_no, SUM(balance) AS total_balance
FROM accounts
GROUP BY customer_no
HAVING SUM(balance) &gt;= 0 ;


To get the total sum of all the above customer balances:

SELECT SUM(total_balance) AS super_total_balance
FROM
  ( SELECT SUM(balance) AS total_balance
    FROM accounts
    GROUP BY customer_no
    HAVING SUM(balance) &gt;= 0
  ) AS t ;


or with a rather cryptic variation:

SELECT TOP (1)
       SUM(SUM(balance)) OVER () AS super_total_balance
FROM accounts
GROUP BY customer_no
HAVING SUM(balance) &gt;= 0 ;