Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group null and empty string together

I want to group the NULL and empty fields in a column together .

I tried the below script

SELECT
  CASE
    WHEN test IS NULL OR test= ''
    THEN ''
    ELSE test
  END as 'test' 
from firm 
group by test

If we are having the values NULL,'',Test1,Test2 in the column test,the above query will create two groups with NULL values as below.

1 NULL

2 NULL

3 Test1

4 Test2

What I want is a grouping shown below.

1 NULL or ''

2 Test1

3 Test2
like image 827
Geethu Avatar asked Jan 06 '14 08:01

Geethu


2 Answers

Try this hope this helps you

SELECT
  CASE
    WHEN test IS NULL OR test= ''
    THEN ''
    ELSE test
  END as 'test' 
from firm 
group by CASE WHEN test IS NULL OR test = '' THEN '' ELSE test END

OR

SELECT
  CASE
    WHEN test IS NULL OR test= ''
    THEN ''
    ELSE test
  END as 'test' 
from firm 
group by isnull(test, '')
like image 143
Jade Avatar answered Nov 18 '22 04:11

Jade


Your CASE is reinventing COALESCE:

SELECT
  COALESCE(test, '') as test
from firm 
group by COALESCE(test, '')

or simply:

SELECT DISTINCT
  COALESCE(test, '') as test
from firm 
like image 6
Bohemian Avatar answered Nov 18 '22 03:11

Bohemian