Select 单列中的多行由换行符分隔
Select Multiple rows in single column separated by New Line
我有一个 table,其值如下所示。
Id Name Fruit
------------
1 Jon Apple
------------
2 Jon Orange
------------
3 Jon Grape
------------
4 Mike Apple
------------
5 Mike Orange
-------------
如何在 mysql 中将列区分为这样的内容?
Name Fruit
----------
Jon Apple
Orange
Grape
-----------
Mike Apple
Orange
-----------
应该这样做
SELECT name, GROUP_CONCAT(fruit SEPARATOR '\n') FROM your_table GROUP BY name
更新以添加编号:
SELECT name ,
GROUP_CONCAT(CONCAT (rn,')',fruit) SEPARATOR '\n')
FROM (
SELECT *
,ROW_NUMBER() OVER (PARTITION BY name) AS rn
FROM your_table
) SQ
GROUP BY name
另一种选择也是使用 joins
来实现此要求。
select
case when t1.id = t2.id then t1.name else '' end
, t3.fruits
from
(select min(id) id, name from testA
group by name) t1
left join
testA t2 on t2.name = t1.name
left join
testA t3 on t3.id = t2.id
order by t2.id asc
参见 dbfiddle。
我有一个 table,其值如下所示。
Id Name Fruit
------------
1 Jon Apple
------------
2 Jon Orange
------------
3 Jon Grape
------------
4 Mike Apple
------------
5 Mike Orange
-------------
如何在 mysql 中将列区分为这样的内容?
Name Fruit
----------
Jon Apple
Orange
Grape
-----------
Mike Apple
Orange
-----------
应该这样做
SELECT name, GROUP_CONCAT(fruit SEPARATOR '\n') FROM your_table GROUP BY name
更新以添加编号:
SELECT name ,
GROUP_CONCAT(CONCAT (rn,')',fruit) SEPARATOR '\n')
FROM (
SELECT *
,ROW_NUMBER() OVER (PARTITION BY name) AS rn
FROM your_table
) SQ
GROUP BY name
另一种选择也是使用 joins
来实现此要求。
select
case when t1.id = t2.id then t1.name else '' end
, t3.fruits
from
(select min(id) id, name from testA
group by name) t1
left join
testA t2 on t2.name = t1.name
left join
testA t3 on t3.id = t2.id
order by t2.id asc
参见 dbfiddle。