Parthapratim Neog Parthapratim Neog - 5 months ago 6
SQL Question

Group by only particular values of a column

Consider the following table for example

+----+-------+--------------+
| ID | TYPE | NAME |
+----+-------+--------------+
| 1 | 13 | Free color |
| 2 | 15 | Free food |
| 3 | 15 | Free burger |
| 4 | 17 | Free cloths |
| 5 | 13 | Free crayons |
| 6 | 12 | Free wood |
+----+-------+--------------+


I am trying to build a query which would
group by
only type 15, if I use the normal
group by
, on the column
type
, it would group by all the types, even type 13, which I don't want. I only want to group by the column type on specific values(here 15). Is it possible in MySQL? If so, how?

The expected result would look something like this:

+----+-------+--------------+
| ID | TYPE | NAME |
+----+-------+--------------+
| 1 | 13 | Free color |
| 2 | 15 | Free food |
| 4 | 17 | Free cloths |
| 5 | 13 | Free crayons |
| 6 | 12 | Free wood |
+----+-------+--------------+

Answer

you can do it like this:

SELECT *
FROM table_name
GROUP BY IF(`Type` = 15, 0 , id);
Comments