如何显示加在一起时的行等于零

时间:2013-09-30 10:57:30

标签: sql

一直在寻找解决这个问题的几个星期但是空白了。

我有类似的数据表:

client_ref  supplier_key  client_amount
1111        GBP           10
1111        GBP           -10
1111        EUR           50
2222        CHF           -22.5
2222        CHF           -20
3333        EUR           -27
3333        EUR           -52
3333        EUR            79

我需要提取client_ref和supplier_key匹配的所有项目,以及client_amount的总数等于零。输出看起来像这样:

client_ref  supplier_key  client_amount
1111        GBP           10
1111        GBP           -10
3333        EUR           -27
3333        EUR           -52
3333        EUR            79

我写了以下内容以返回总计,但我需要您提供的任何帮助来更改此选项以显示构成总计的行而不仅仅是整体结果。

SELECT tbis.client_ref ,tbis.supplier_key ,sum(tbis.client_amount) 
FROM [XXXX].[dbo].[transaction] tbis 
WHERE tbis.tbis.client_amount !=0 
GROUP BY tbis.client_ref, tbis.supplier_key 
HAVING sum(tbis.client_amount) =0 
ORDER BY sum(tbis.client_amount)

希望这是有道理的,我的第一篇文章还可以。请随时批评我的帖子。

6 个答案:

答案 0 :(得分:1)

请改为尝试:

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;

答案 1 :(得分:0)

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 

答案 2 :(得分:0)

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

http://sqlfiddle.com/#!3/a3447/8/0

演示

答案 3 :(得分: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

答案 4 :(得分:0)

一种可能的方法是使用SUM()窗口函数:

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

答案 5 :(得分:-1)

对您想要的数据进行新查询,并通过内部联接将其连接到生成总和的查询,以将其限制为您想要的行。