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
 Help me to build this query

Author  Topic 

Jayachandran
Starting Member

1 Post

Posted - 2010-07-28 : 05:12:13
I have a table with three columns

Office,Amount and Date

I need to sum up the amount for office and need to know till that particular date what the amount?

For example,

Let the records be

Office Amount Date
Office1 1000 10th July 2010
Office1 500 11th July 2010
Office1 1000 12th July 2010
Office2 1000 10th July 2010
Office2 1000 11th July 2010
Office2 1000 12th July 2010
Office3 1000 9th July 2010
Office3 1000 10th July 2010
Office3 1000 11th July 2010
Office3 1000 12th July 2010

I need the out put has

Office Amount Date
Office1 1000 10th July 2010
Office1 1500 11th July 2010
Office1 2500 12th July 2010
Office2 1000 10th July 2010
Office2 2000 11th July 2010
Office2 3000 12th July 2010
Office3 1000 9th July 2010
Office3 2000 10th July 2010
Office3 3000 11th July 2010
Office3 4000 12th July 2010

Please help me



Jayachandran

Devart
Posting Yak Master

102 Posts

Posted - 2010-07-28 : 05:41:39
Hello,

You can try this:

SELECT
t.office,
(SELECT SUM(amount) FROM <your_table_name> WHERE office=t.office AND date<=t.date) AS amount,
t.date
FROM
<your_table_name> t
ORDER BY
t.office,t.date;

Best regards,


Devart Team
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2010-07-28 : 07:01:49
Another method is to use quirky update
http://beyondrelational.com/blogs/madhivanan/archive/2009/06/10/quirky-update-in-sql-server.aspx

Madhivanan

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

Sachin.Nand

2937 Posts

Posted - 2010-07-28 : 07:16:16
I just fail to understand why it is not possible using normal CTE

declare @tbl as table(id int ,Office varchar(40),amount int)
insert into @tbl
select 1,'Office1', 1000 union all
select 2,'Office1' ,500 union all
select 3,'Office1', 1000 union all
select 4,'Office2', 1000 union all
select 5,'Office2', 1000 union all
select 6,'Office2', 1000 union all
select 7,'Office3', 1000 union all
select 8,'Office3', 1000 union all
select 9,'Office3', 1000 union all
select 10,'Office3',1000

;with cte
as
(
select Office,id,amount,amount as amt from @tbl

union all
select t.Office,t.id,t.amount,(t.amount+c.amt) as amt from @tbl as t
inner join cte c on t.id=c.id+1 and t.Office=c.Office
)

select * from cte order by office







Limitations live only in our minds. But if we use our imaginations, our possibilities become limitless.

PBUH
Go to Top of Page
   

- Advertisement -