开发者

Need Sql Queries for the scenario

开发者 https://www.devze.com 2023-01-05 10:57 出处:网络
Trans IdDateDescriptionCreditDebit 112/05/2009 Amount Deposited10001000 215/05/2009 Amount withdrawn-500500
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 is the primary key

I need the output as follows

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

Need Sql query to generate the output


I think this does what you want:

SELECT TransId, Date, Description, ABS(Credit) AS Amount
FROM transactions
UNION ALL
SELECT NULL, NULL, 'balance', SUM(Credit)
FROM transactions;

Result:

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            


You could use a case statement to find the maximum, and abs to ensure a positive number:

select  [trans id]
,       date
,       description
,       abs(case when credit > debit then credit else debit end) as Amount
from    YourTable

Re-reading your question, I doubt this is the answer you're looking for. Please explain in a bit more detail.

0

精彩评论

暂无评论...
验证码 换一张
取 消