Been searching for a few weeks for a solution to this but have come up blank.
I have table of data similar to this:
client_ref supplier_key client_amou
Try this instead:
SELECT t1.*
FROM transactions AS t1
INNER JOIN
(
SELECT
tbis.client_ref ,
tbis.supplier_key,
sum(tbis.client_amount) AS total
FROM transactions tbis
WHERE tbis.client_amount !=0
GROUP BY tbis.client_ref, tbis.supplier_key
HAVING sum(tbis.client_amount) =0
) AS t2 ON t1.client_ref = t2.client_ref
AND t1.supplier_key = t2.supplier_key
ORDER BY t2.total;
SELECT
*
FROM
tbis
INNER JOIN
(
SELECT
client_ref, supplier_key
FROM
tbis
GROUP by client_ref, supplier_key
HAVING sum(client_amount) = 0
) match
ON match.client_ref = tbis.client_ref
AND match.supplier_key = tbis.supplier_key
Demo at http://sqlfiddle.com/#!3/a3447/8/0
SELECT t.* FROM Table1 AS t INNER JOIN
(SELECT [client_ref], [supplier_key], SUM([client_amount]) as Total
FROM Table1 GROUP BY [client_ref], [supplier_key]) AS sumTable
ON t.[client_ref] = sumTable.[client_ref] AND
t.[supplier_key] = sumTable.[supplier_key]
WHERE Total = 0;
SAMPLE FIDDLE
One possible approach is to use the SUM() windowing function:
SELECT *
FROM
( SELECT tbis.client_ref ,tbis.supplier_key,tbis.client_amount,
SUM(tbis.client_amount) OVER (
PARTITION BY tbis.client_ref, tbis.supplier_key) AS total_client_amount
FROM [XXXX].[dbo].[transaction] tbis
WHERE tbis.client_amount !=0
)
WHERE total_client_amount = 0
SQL Fiddle
Make a new query for the data you want and join it by inner join to the query that produces the sums to restrict it to the lines you want.
SELECT client_ref ,supplier_key ,sum(client_amount)
FROM transaction
WHERE client_amount <> 0
GROUP BY client_ref, supplier_key
HAVING sum(client_amount) = 0