这是我的表:
+--------+-----------+
|country |city |
+--------+-----------+
| india | hydrabad |
| india | bangalore |
| india | mumbai |
| UK | London |
| UK | france |
| UK | Conberry |
| USA | new jersy |
| USA | texas |
| USA | New YORK |
+--------+-----------+
我想这样表现出来:
+--------+----------+--------+------------+
|country |city1 |city2 |city3 |
+--------+----------+--------+------------+
| india | hydrabad | mumbai | Bangalore |
| UK | London | France | Conberry |
| USA | newjersy | texas | New YORK |
+--------+----------+--------+------------+
如何编写MySQL查询来执行此操作?
答案 0 :(得分:2)
你可以使用这样的查询:
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;
<强>样品强>
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]>
答案 1 :(得分:1)
使用连接查询(如果城市已修复)
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
如果您想在单列使用中使用逗号分隔的所有城市,请使用
SELECT country, GROUP_CONCAT(city) as Cities FROM tblname GROUP BY country
答案 2 :(得分:0)
尝试此查询,
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