2

I have a table such as:

table a
+------+-------+
| v1   | v2    |
+------+-------+
|    1 | one   |
|    2 | two   |
|    3 | two   |
|    4 | two   |
|    5 | NULL  |
|    6 | NULL  |
|    7 | three |
|    8 | three |
+------+-------+

I want to group the data in this table by the column 'v2'...

mysql> select * from a group by v2 order by v1;
+----+-------+
| v1 | v2    |
+----+-------+
|  1 | one   |
|  2 | two   |
|  5 | NULL  |
|  7 | three |
+----+-------+

... but leave the NULL values on separate rows. Is it possible to prevent the NULL values from being collapsed into a single row?

0

1 Answer 1

5

This would accomplish what you're asking:

select min(v1) as v1, v2 from a group by v2, ifnull(v2, v1) order by v1;

This would group by v2, unless it is NULL, in which case it would group by v1. Since your two NULL values have two different values for v1, it would split them apart.

Sign up to request clarification or add additional context in comments.

2 Comments

I need all the v1-s that are on the rows with NULL values, but for the other rows it doesn't matter which of the v1-s remain. That table a comes from another select statement that has LEFT JOIN-s, which produces the NULL-s. (The v1-s are ID values...)
@gregn3 OK, makes sense to me now... I've updated the answer accordingly.

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.