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
 CASE,WHERE and SUM

Author  Topic 

ashishashish
Constraint Violating Yak Guru

408 Posts

Posted - 2010-02-05 : 01:03:08
Hi All
i am facing a problem writing in a query
My current query is like this

SELECT SUM(col1) from table where mydate<=getdate()
UNION ALL
SELECT SUM(col1) from table where mydate<=getdate()-7
UNION ALL
SELECT SUM(col1) from table where mydate<=getdate()-14
UNION ALL
SELECT SUM(col1) from table where mydate<=getdate()-21

I like to have this query in a single statement may be by using case or something like this.
Well am not able to figure it out
So can anybody help me in this.

iF theRe iS a wAy iN tHen theRe iS a wAy oUt..

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2010-02-05 : 01:12:53
quote:
I like to have this query in a single statement may be by using case or something like this.

With the same result return with the sum() still in rows ?


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

Go to Top of Page

ashishashish
Constraint Violating Yak Guru

408 Posts

Posted - 2010-02-05 : 01:15:30
no you can take it in column as Current Week value,Last Week Value, 2 Weeks Ago and 3 Weeks Ago, actually i want it in column so i want it in case statement.
Thanks for Asking

iF theRe iS a wAy iN tHen theRe iS a wAy oUt..
Go to Top of Page

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2010-02-05 : 01:23:00
[code]
select sum(case when mydate <= getdate() then col1 end),
sum(case when mydate <= getdate() - 7 then col1 end),
. . .
from table
[/code]


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

Go to Top of Page

ashishashish
Constraint Violating Yak Guru

408 Posts

Posted - 2010-02-05 : 01:29:57
Thanks it worked like a charm, what i am doing wrong is putting my case condition in where clause.
Thanks a Lot
In between is there any way exists to get same results when put case in where condition or i am just wasting my time, dont mind just hungry to learn more.
Thanks Again

iF theRe iS a wAy iN tHen theRe iS a wAy oUt..
Go to Top of Page
   

- Advertisement -