How to display rows that when added together equal zero

后端 未结 6 1686
一生所求
一生所求 2021-01-29 01:39

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         


        
相关标签:
6条回答
  • 2021-01-29 01:48

    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;
    
    • SQL Fiddle Demo
    0 讨论(0)
  • 2021-01-29 01:51
    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

    0 讨论(0)
  • 2021-01-29 01:51
    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

    0 讨论(0)
  • 2021-01-29 02:02

    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

    0 讨论(0)
  • 2021-01-29 02:07

    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.

    0 讨论(0)
  • 2021-01-29 02:08
    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 
    
    0 讨论(0)
提交回复
热议问题