Trans Id Date Description Credit Debit 1 12/05/2009 Amount Deposited 1000 1000 2 15/05/2009 Amount withdrawn -500 500 3 20/05/2009 Deposited 2000 2500 4 25/05/2009 Amount withdrawn -1000 1500 1500
Trans ID是主键
我需要输出如下
Trans Id Date Description Amount 1 12/05/2009 Amount Deposited 1000 2 15/05/2009 Amount withdrawn 500 3 20/05/2009 Deposited 2000 4 25/05/2009 Amount withdrawn 1000 balance 1500
需要Sql查询来生成输出
答案 0 :(得分:2)
我认为这可以满足您的需求:
SELECT TransId, Date, Description, ABS(Credit) AS Amount
FROM transactions
UNION ALL
SELECT NULL, NULL, 'balance', SUM(Credit)
FROM transactions;
结果:
TransId Date Description Amount 1 2009-05-12 Amount Deposited 1000 2 2009-05-15 Amount Withdrawn 500 3 2009-05-20 Deposited 2000 4 2009-05-25 Amount Withdrawn 1000 NULL NULL balance 1500
答案 1 :(得分:0)
您可以使用case语句查找最大值,使用abs来确保正数:
select [trans id]
, date
, description
, abs(case when credit > debit then credit else debit end) as Amount
from YourTable
重新阅读你的问题,我怀疑这是你正在寻找的答案。请详细解释一下。