I have table which has 2 columns empid & depid. This table does not have any primary key. Below is the data of the table.
+-------+-------+
| empid | depid |
+-------+-------+
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 1 | 4 |
| 2 | 1 |
| 2 | 2 |
| 2 | 3 |
| 2 | 4 |
+-------+-------+
Now to select all the depids for an employee I wrote below query.
select empid, group_concat(depid separator ':') from emp group by empid;
It is giving me expected output.
+-------+-----------------------------------+
| empid | group_concat(depid separator ':') |
+-------+-----------------------------------+
| 1 | 1:2:3:4 |
| 2 | 1:2:3:4 |
+-------+-----------------------------------+
Now I want select only those depids which are greater than 2. How can I use if with group_concat?
The GROUP_CONCAT() function in MySQL is used to concatenate data from multiple rows into one field. This is an aggregate (GROUP BY) function which returns a String value, if the group contains at least one non-NULL value. Otherwise, it returns NULL.
Because the GROUP_CONCAT function is an aggregate function, to sort the values, you must use the ORDER BY clause inside the function, not in the ORDER BY in the SELECT statement. The SELECT clause returns one string value so the ORDER BY clause does not take any effect in this statement.
Try as below :
SELECT empid, GROUP_CONCAT(IF(depid > 2, depid, NULL) SEPARATOR ':')
FROM emp
GROUP BY empid;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With