如何在sql中找到同一列的行之间的差异

时间:2015-10-29 08:58:52

标签: sql sql-server-2008

enter image description here

question->写一个查询显示所有那些账号,存款,提款,其中提款金额多于存款金额。

2 个答案:

答案 0 :(得分:0)

试试这个(你也可以通过SELF JOIN来做):

;WITH D AS
(
SELECT ACNUMBER, SUM(TRANSACTION) AS Deposit
FROM TABLE_NAME 
WHERE TRANSACTION_TYPE = 'Deposit'
GROUP BY ACNUMBER
)
, W as
(
SELECT ACNUMBER, SUM(TRANSACTION) AS Withdrawal
FROM TABLE_NAME 
WHERE TRANSACTION_TYPE = 'Withdrawal'
GROUP BY ACNUMBER

)
SELECT D.ACNUMBER, d.Deposit, w.Withdrawal

FROM D 
INNER JOIN W
ON D.ACNUMBER = W.ACNUMBER
WHERE d.Deposit < w.Withdrawal

答案 1 :(得分:0)

您不应按交易类型分组。试试这个

select acnumber,sum(transaction_amount * case when transaction_type = 'deposit' then 1 else -1 end) as amount 
from trandetails 
group by acnumber
order by acnumber asc 

您可能只对金额为负的行感兴趣,因为这些是撤销的帐户&gt;存款。在这种情况下,添加一个过滤器:

select acnumber,sum(transaction_amount * case when transaction_type = 'deposit' then 1 else -1 end) as amount 
from trandetails 
group by acnumber
having sum(transaction_amount * case when transaction_type = 'deposit' then 1 else -1 end) < 0
order by acnumber asc