Skip to content
Advertisement

How to combine few row record in mySQL?

I am trying to combine few rows combine and output as 1 row. Here is my example and my expected output. I have tried group_concat and put if/ case condition in query but it seems somehow cannot output as I expected. Thanks in advance.

Data:
id | Type   | Name       |Supermarket
1    Fruit    Apple       East
2    Fruit    Orange      West
3    Fruit    Pear        Central

Expected Output:
Type   |East    |West      |Central
Fruit   Apple    Orange     Pear

Advertisement

Answer

The duplicate questions I looked up for this didn’t have very clear answers IMHO, so I’ll write one:

First we need to spread the data we are interested in across 3 columns:

SELECT
  type,
  CASE WHEN supermarket = 'east' THEN name END as east,
  CASE WHEN supermarket = 'west' THEN name END as west,
  CASE WHEN supermarket = 'central' THEN name END as central
FROM t

Run that and you’ll see the data spread out to 3 rows and 3 columns, mostly nulls. Now we need to get rid of the nulls. If we use MAX() on every column with nulls we will hide everything except the one cell that has a value (max will always pick a value over null)

SELECT
  type,
  MAX(CASE WHEN supermarket = 'east' THEN name END) as east,
  MAX(CASE WHEN supermarket = 'west' THEN name END) as west,
  MAX(CASE WHEN supermarket = 'central' THEN name END) as central
FROM t
GROUP BY type
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement