views:

227

answers:

4

Hi,

I have to create a query that checks across several different columns, and if any of them have a 1, I want to return true.

Ideal output would be along the lines of:

ID:55
Name:John Doe
IsDealerType1:True
IsDealerType2:True
IsDealerType3:False
IsDealerType4:False
IsDealerType5:True

The problem is, instead of those 5 dealer columns, I have about 20 columns named 1a, 1b, 1c, 1d, etc. If any of the "1" columns is true, then IsDealerType1 should be true.

I'm trying to avoid writing something in the VB.NET code to check each and every column, just because that sheer ugliness should be easy to avoid in SQL - if only I knew how to do it - but I'm not sure how to construct the query. I've been trying stuff like...

SELECT id, 
      name, 
      (1a or 1b or 1c or 1d) as IsDealerType1, 
      (2a or 2b or 2c or 2d) as IsDealerType2 
where id = 55

... but obviously, I'm not doing it right.

Any help is appreciated. Thanks!

+5  A: 

CASE WHEN (1a + 1b + 1c + 1d) > 0 THEN 1 ELSE 0 END as IsDealerType1

Russell Steen
a lot nicer than case 1a when true then true else case 1b when true then true .... else false end etc.
Shawn Simon
I didn't know which one to check because they will all work - thanks for the quick responses!
Bryan
In SQL Server the BIT type does not have an 'add' operator though, so 1a+1b would give error 8117 'Operand data type bit is invalid for add operator.'. This works only if 1a...1d is stored as numeric (tinyint, smallint, int etc), or a an aditonal cast on each 1a..1d column is required.
Remus Rusanu
+8  A: 

I like Russel's, but I'm gonna add this as well:

CASE WHEN 1 IN (1a,1b,1c,1d) THEN 1 ELSE 0 END As IsDealerType1
Joel Coehoorn
Slick. Not my first thought, but I recently discovered this use of IN.
Rob Garrison
+1  A: 

In SQL the BIT types cannot be used in boolean expressions (d'oh!!), they need to be compared with ints:

SELECT id, name, 
   cast(
    case when ([1a]=1 or [1b]=1 or [1c]=1 or [1d]=1) then 1 else 0 end
    as bit) as IsDealerType1,
    cast(case when ([2a]=1 or [2b]=1 or [2c]=1 or [2d]=1) then 1 else 0 end
    as bit) as IsDealerType2 
from [table]
where id = 55
Remus Rusanu
..but bit can use bitwise operators. Pls see my answer
gbn
+2  A: 

Use the SQL bitwise OR operator. Avoids comparisons and casts.

Example: Joel's answers passes integer 1 or 0 to the client, where you'd arguably expect bit (boolean). Remus' answers needs casts and comparisons.

SELECT id, 
      name, 
      (1a | 1b | 1c | 1d) as IsDealerType1, 
      (2a | 2b | 2c | 2d) as IsDealerType2 
where id = 55
gbn
+1 I learned something new
Remus Rusanu