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 2008 Forums
 Transact-SQL (2008)
 Subtract value from two rows in one collum

Author  Topic 

Madehhh
Starting Member

1 Post

Posted - 2011-03-10 : 10:57:32
Subtract value from two rows in one collum ,

hi i need to calculate the sales from every week of a shop, right now i have a querie that gives me the sum of sales from all weeks , every week. i need to make the difference from the rows so i get what was actually sold in every particular week.

please help thanks

lappin
Posting Yak Master

182 Posts

Posted - 2011-03-10 : 11:58:59
Use your existing query for weekly total and join this to same table but where week = week-1

This works except from last week in Dec to 1st week in Jan

Select T1.*, T2.wklyTotal as LastWeekTotal, T1.wklyTotal - T2.wklyTotal as WklyDiff from (
SELECT DATEPART( wk, [DT]) as ThisWeek

,Sum([Value]) as wklyTotal

FROM TableA

Group By DATEPART( wk, [DT])) as T1
JOIN
(SELECT DATEPART( wk, [DT]) as ThisWeek

,Sum([Value]) as wklyTotal

FROM TableA

Group By DATEPART( wk, [DT]))T2
on T1.ThisWeek =T2.ThisWeek-1
GO
Go to Top of Page
   

- Advertisement -