This is my table:
+--------+-----------+
|country |city |
+--------+-----------+
| india | hydrabad |
| india | bangalore |
| india | mumbai |
| UK | London |
| UK | france |
| UK | Conberry |
| USA | new jersy |
| USA | texas |
| USA | New YORK |
+--------+-----------+
I want to show it like this:
+--------+----------+--------+------------+
|country |city1 |city2 |city3 |
+--------+----------+--------+------------+
| india | hydrabad | mumbai | Bangalore |
| UK | London | France | Conberry |
| USA | newjersy | texas | New YORK |
+--------+----------+--------+------------+
How can I write a MySQL query to do this?
you can use a query like this:
SELECT country,
GROUP_CONCAT(IF(nr=0,city,NULL)) AS city1,
GROUP_CONCAT(IF(nr=1,city,NULL)) AS city2,
GROUP_CONCAT(IF(nr=2,city,NULL)) AS city3
FROM (
SELECT
@nr := IF(@country_last = c.country, @nr:=(@nr+1),@nr:=0) AS nr,
@country_last := c.country AS country,
c.city
FROM country c
CROSS JOIN (SELECT @nr := 0, @country_last := '') param
ORDER BY c.country
) AS d
GROUP BY country;
sample
MariaDB [yourschema]> select * from country;
+---------+-----------+
| country | city |
+---------+-----------+
| india | hydrabad |
| india | bangalore |
| india | mumbai |
| uk | London |
| uk | france |
| uk | Conberry |
+---------+-----------+
6 rows in set (0.00 sec)
MariaDB [yourschema]>
MariaDB [yourschema]> SELECT country,
-> GROUP_CONCAT(IF(nr=0,city,NULL)) AS city1,
-> GROUP_CONCAT(IF(nr=1,city,NULL)) AS city2,
-> GROUP_CONCAT(IF(nr=2,city,NULL)) AS city3
-> FROM (
-> SELECT
-> @nr := IF(@country_last = c.country, @nr:=(@nr+1),@nr:=0) AS nr,
-> @country_last := c.country AS country,
-> c.city
-> FROM country c
-> CROSS JOIN (SELECT @nr := 0, @country_last := '') param
-> ORDER BY c.country
-> ) AS d
-> GROUP BY country;
+---------+----------+-----------+----------+
| country | city1 | city2 | city3 |
+---------+----------+-----------+----------+
| india | hydrabad | bangalore | mumbai |
| uk | London | france | Conberry |
+---------+----------+-----------+----------+
2 rows in set (0.00 sec)
MariaDB [yourschema]>
Use join query for it( If cities are fixed)
SELECT A.country,A.city city1,B.city city2,C.city city3 FROM tblname A
LEFT JOIN tblname B ON A.country=B.country
LEFT JOIN tblname C ON A.country=C.country
WHERE A.city!=B.city and A.city!=C.city and B.city!=C.city
GROUP BY A.country
If you want to use all cities separated by comma in single column use like this,
SELECT country, GROUP_CONCAT(city) as Cities FROM tblname GROUP BY country
Try this query,
Select Country, City1, City2, City3
From
(
Select Country, City,
'City'+
cast(row_number() over(partition by Country order by Country)
as varchar(10)) ColumnSequence
From Country
) Temp
Pivot
(
Max(City)
For ColumnSequence in (City1, City2, City3)
) Piv
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.