David David - 1 month ago 9
MySQL Question

MySQL; GROUP BY but only if column is not empty

I have the following SQL query:

SELECT * FROM my_table GROUP BY B,D,F;


If there are some rows where
B
is empty and
D
is empty AND
F
is empty, it'll grouped to a single row where all the three columns are empty.

But instead I want: in case all three columns (B, D, F) of a row are empty don't group this row show it.

Means: If I have the following:

enter image description here

result should be:

enter image description here

How can I do this?

Answer Source

Firstly, you are selecting * with group by !! not sure if this is going to work with you.

Anyway, to achieve what you want try this

SELECT B,D,F
FROM your_table
WHERE NOT (B='' AND D='' AND F='')
GROUP BY B,D,F

UNION

SELECT B,D,F
FROM your_table
WHERE B='' AND D='' AND F=''