How to Concatenate Column Values from Multiple Rows

Just want to share with you on how to concatenate or combine one or more values from multiple rows. This SQL code is part of my “Online Hotel Reservation” project.

The idea here is to group column values while concatenating the other column to avoid duplicate records.

Here’s an example:

I have the following record on my table:

Room Type         	Extras           	Price
Budget Room       	Extra Person     	250
Economy Room	  	Extra Person     	250
Budget Room       	Breakfast        	350
Economy Room	  	Breakfast        	350
Superior Room     	Extra Person     	400

Then I want the following result:

Room Type                     	Extras           	Price
Budget Room & Economy Room    	Extra Person     	250
Budget Room & Economy Room    	Breakfast        	350
Superior Room         	      	Extra Person     	400

As you can see the Budget room and Economy room was concatenated to group Extras and Price field.

SOLUTION: Here’s the SQL statement specific to MySQL.

  1. SELECT
  2.     GROUP_CONCAT(`Room Type` SEPARATOR ' & ') TYPE AS `Room Type`,
  3.     Extras,
  4.     Price
  5. FROM table1
  6. GROUP BY Extras, Price

Comments

Add new comment