SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 sql
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

profsarma
Starting Member

India
1 Posts

Posted - 07/24/2013 :  10:24:19  Show Profile  Reply with Quote

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
Flowing Fount of Yak Knowledge

Germany
8765 Posts

Posted - 07/24/2013 :  10:33:32  Show Profile  Visit webfred's Homepage  Reply with Quote
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

India
52317 Posts

Posted - 07/25/2013 :  00:52:50  Show Profile  Reply with Quote
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

India
22761 Posts

Posted - 07/28/2013 :  10:57:52  Show Profile  Send madhivanan a Yahoo! Message  Reply with Quote
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
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.08 seconds. Powered By: Snitz Forums 2000