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
 IF statement with a OR?

Author  Topic 

Maverick_
Posting Yak Master

107 Posts

Posted - 2013-08-20 : 06:48:54
Hi guys,

I am trying to write an SQL query which goes something like:

count( if( {Feature Label} LIKE "%AB%" OR {Feature Label} LIKE "%CR",1,0) )

But it doesn't quite work. How can you write an OR inside an If statement?

Robowski
Posting Yak Master

101 Posts

Posted - 2013-08-20 : 07:25:54
SELECT
COUNT(1) AS TotalCount
FROM
Table
WHERE
Feature_Label LIKE '%ABC%' OR Feature_Label LIKE '%CR' --Not sure what the 1,0 is for sorry?

Or if you want a count for the labels

SELECT
Feature_label, COUNT(1) AS TotalCount
FROM
Table
WHERE
Feature_Label LIKE '%ABC%' OR Feature_Label LIKE '%CR'
GROUP BY
Feature_Label
Go to Top of Page

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-08-20 : 08:23:24
quote:
Originally posted by Maverick_

Hi guys,

I am trying to write an SQL query which goes something like:

count( if( {Feature Label} LIKE "%AB%" OR {Feature Label} LIKE "%CR",1,0) )

But it doesn't quite work. How can you write an OR inside an If statement?

Are you using Microsoft SQL Server? Assuming you are, what you need is something like this:
SUM(
CASE WHEN
[Feature Label] LIKE '%AB%' OR [Feature Label] LIKE '%CR%' THEN 1
ELSE 0
END
)
Note, I am using a CASE expression rather than if. IF is a control flow construct which cannot be used in this situation. Also, use SUM rather than COUNT.
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2013-08-20 : 09:16:49
Also see why SUM is preferred over COUNT http://beyondrelational.com/modules/2/blogs/70/posts/19240/conditional-aggregation-sum-vs-count.aspx

Madhivanan

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

- Advertisement -