2

I have a table tb1 like this:

id  | building  | id_connect |  
====+==========+============
1 |     1    |       "328abbc"    
2 |     3    |       "328abbc"    
3 |     4    |       "212a3b"    
4 |     1    |       "212a3b"  
5 |     2    |       ""  
6 |     2    |       ""
7 |     7    |       ""

I need to get the count of the distinct id_connect if the string is different to "", but each empty string ("") has to add 1...

In the example, the required result would be 5 (one "328abbc", one "212a3b" and the three ""), but I only obtain 3 with

SELECT COUNT(DISTINCT(id_connect))
FROM tb1
0

2 Answers 2

3
SELECT
    COUNT(CASE WHEN id_connect='' THEN 1 END)
  + COUNT(DISTINCT NULLIF(id_connect, ''))
FROM tb1
Sign up to request clarification or add additional context in comments.

3 Comments

See it running as an alternative on @Bohemian's sqlfiddle here.
@eggyal you're a noob: COUNT(CASE WHEN id_connect='' THEN 1 END) is identical to COUNT(id_connect='')
Sorry - I meant SUM(id_connect='') - see here. It's more "leet" than the wordy case
-1

This works:

SELECT COUNT(DISTINCT(if(id_connect = '', concat(id, 'text not found in id_connect'), id_connect)))
FROM tb1

Output:

5 

See it running here.

2 Comments

@Bohemian: What if a blank's id matches an id_connect?
@eggyal then add something to it (see edited answer) - don't be pedantic

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.