Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 sql

Author  Topic 

profsarma
Starting Member

1 Post

Posted - 2013-07-24 : 10:24:19

I had a table and records like this

acno status amount
111 cr 1000
111 db 2000
111 db 1000
111 cr 1000

now I need to get balance now (credit - debit) using sql single query, please

mvvssarma

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2013-07-24 : 10:33:32
This?
declare @sample table (acno int, status char(2), amount decimal(12,2))

insert @sample
select 111, 'cr', 1000 union all
select 111, 'db', 2000 union all
select 111, 'db', 1000 union all
select 111, 'cr', 1000 union all
select 222, 'cr', 500 union all
select 222, 'db', 100

select
acno,
sum(case when status='cr' then amount else 0 end) - sum(case when status='db' then amount else 0 end) as bal
from
@sample
group by acno



Too old to Rock'n'Roll too young to die.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-07-25 : 00:52:50
actually you could just wrap them inside single sum
like

select
acno,
sum(case status when 'cr' then amount when 'db' then -1 * amount else 0 end) as bal
from
@sample
group by acno


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2013-07-28 : 10:57:52
quote:
Originally posted by visakh16

actually you could just wrap them inside single sum
like

select
acno,
sum(case status when 'cr' then amount when 'db' then -1 * amount else 0 end) as bal
from
@sample
group by acno


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs



or shortly


select
acno,
sum(case status when 'cr' then amount when 'db' then -amount else 0 end) as bal
from
@sample
group by acno



Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -