views:

278

answers:

3

I'm trying to count how many distinct value of FLOOR there is but I don't want the value "B" to count towards the total.

Here is my current code. It counts how many distinct floors there is but it includes the FLOOR "B" when there is one.

 SELECT COUNT(DISTINCT FLOOR) as NB_FLOORS FROM TABLE_ID

The table looks something like this :

 FLOOR     ROOM
 B         Bedroom
 1         Kitchen
 1         Bathroom
 2         Bedroom
 2         Bedroom

The result in this case shoudl be 2 because there is 2 floors ("B" being the basement which doesn't count as a floor). I'm currently getting 3 with the code I posted.

Thanks.

+8  A: 
SELECT COUNT(DISTINCT FLOOR) as NB_FLOORS FROM TABLE_ID WHERE FLOOR <> 'B'
waqasahmed
Haha, how did I not think of that. I need to start thinking simple instead of complicated... Thanks!
Enkay
np :).. anytime
waqasahmed
A: 

Here's a solution that relies on COUNT() ignoring NULL:

SELECT COUNT(DISTINCT CASE FLOOR = 'B' THEN NULL ELSE FLOOR END) AS NB_FLOORS
FROM TABLE_ID;

Another thought: assuming floor numbers always start at 1 and don't skip numbers, you could simply return the MAX():

SELECT MAX(FLOOR) AS NB_FLOORS FROM TABLE_ID;
Bill Karwin
Thanks! Unfortuantely method #2 wouldn't work in this case but I learned something with the first method you suggested.
Enkay
A: 

If you want a more general solution, use a regular expression

SELECT COUNT(DISTINCT FLOOR) as NB_FLOORS FROM TABLE_ID WHERE FLOOR REGEXP '[0-9]'

IniTech
Thanks for answering. While your suggestion would work for this exemple, I happen to have floors that are represented by letters.
Enkay
And you wanted to be able to control whether nor not to count the floors with letters, or so it seemed. Did you ONLY want to exclude "B", if so, the regex would be [^B]. Either way, a regex would make your code more manageable and easier to scale, IMO. What happens when you want to exclude 'R' and 'L' - keep adding ANDS to your original WHERE?
IniTech