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)
 case inside having

Author  Topic 

arkiboys
Master Smack Fu Yak Hacker

1433 Posts

Posted - 2012-12-19 : 12:32:37
Hi,
Is it possible to place case inside having clause?
for example:
select field1, field2, sum(field3)
from tblMain
group by field1, field2
having sum(field3) > 0.1

I would like to do something like:
select field1, field2, sum(field3)
from tblMain
group by field1, field2
case when @param=1 then having sum(field3) > 0.1

so only do the having bit when @param = 1
Any thoughts please?
Thanks

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-12-19 : 12:51:33
Would this work for you?
SELECT field1,
field2,
SUM(field3)
FROM tblMain
GROUP BY
field1,
field2
HAVING
(SUM(field3) > 0.1 AND @param = 1)
OR
ISNULL(@param,0) <> 1;
Go to Top of Page

ScottPletcher
Aged Yak Warrior

550 Posts

Posted - 2012-12-21 : 17:29:38
Yes, you can use CASE in a HAVING clause.

But keep in mind that a CASE statement must evaluate down to a single value, and cannot include any operators or keywords.
Go to Top of Page

arkiboys
Master Smack Fu Yak Hacker

1433 Posts

Posted - 2012-12-22 : 04:13:47
Thank you
Go to Top of Page
   

- Advertisement -