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
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Sum amounts of different ranges in the same table

Author  Topic 

vshal
Starting Member

3 Posts

Posted - 2008-07-29 : 22:08:39
Hi Guys,

I am kinda brand spanking new to SQL and don't know too much other than some simple SELECT statements.

I have a table with the following columns
Entry No - Primary Key
Account No - VARCHAR(20)
Date - DATETIME
Amount - DECIMAL(8,2)

There are many rows in the table and the Account No repeats in many rows as it is not the primary key. The range is from 1000 to 5000.

What I would like to do is to SUM the Amounts of Accounts between 1000 to 2000 and SUM the Amounts of Accounts between 2500 to 3500. Then divide the 1st SUM result with the 2nd SUM result.

This might be a piece of cake but I have been trying to work my way since almost a day now.

thanks people, appreciate your inputs.

singularity
Posting Yak Master

153 Posts

Posted - 2008-07-29 : 22:58:25
select sum(case when [account no] between 1000 and 2000 then amount else 0 end) /
sum(case when [account no] between 2500 and 3500 then amount else 0 end)
from yourtable
Go to Top of Page

vshal
Starting Member

3 Posts

Posted - 2008-07-29 : 23:21:33
Hey,

That worked like magic, how dumb of me wasn't able to figure that out but im not familiar with the CASE statements.

Anyways, Thank you so much for the response and resolution. I wanted to check what happens if these ranges are stored in a different table ?

Thanks,
Vishal
Go to Top of Page

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2008-07-29 : 23:25:44
"what happens if these ranges are stored in a different table ?"
Show us the table structure with sample data


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page
   

- Advertisement -