I'm having some MySQL difficulties in the GROUP BY section of my query.
There is a column I would like to use in the GROUP BY, but that should only be used for a certain condition that depends on a value in a row. Let's say I have this table:
mysql> SELECT * FROM test_table;
+---+---+---+
| a | b | c |
+---+---+---+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 1 | 2 |
| 4 | 2 | 2 |
| 5 | 2 | 3 |
| 6 | 3 | 1 |
| 7 | 2 | 2 |
+---+---+---+
7 rows in set (0.00 sec)
Now I would like to retrieve all the rows, where it should only use GROUP BY on column c, when b === 1. That means I would like to get 6 rows back, because the rows number 2 and 3 should be grouped. So I came up with the following query, which doesn't give me the expected result.
mysql> SELECT * FROM test_table GROUP BY CASE WHEN b = 1 THEN c END;
+---+---+---+
| a | b | c |
+---+---+---+
| 4 | 2 | 2 |
| 1 | 1 | 1 |
| 2 | 1 | 2 |
+---+---+---+
3 rows in set (0.00 sec)
I'm probably missing something within the combination of the CASE statement and the GROUP BY and I hope any of you could help me out a bit.