如果我在 MySQL 中有一个包含以下数据的表:
If I have a table with the following data in MySQL:
id Name Value
1 A 4
1 A 5
1 B 8
2 C 9
如何将其转换为以下格式?
how do I get it into the following format?
id Column
1 A:4,5,B:8
2 C:9
我想我必须使用 GROUP_CONCAT.但我不确定它是如何工作的.
I think I have to use GROUP_CONCAT. But I'm not sure how it works.
select id, group_concat(`Name` separator ',') as `ColumnName`
from
(
select
id,
concat(`Name`, ':', group_concat(`Value` separator ',')) as `Name`
from mytbl
group by
id,
`Name`
) tbl
group by id;
你可以在这里看到它的实现:Sql Fiddle Demo.正是您所需要的.
You can see it implemented here : Sql Fiddle Demo. Exactly what you need.
更新分两步拆分.首先,我们得到一个表,其中包含针对唯一 [Name,id] 的所有值(逗号分隔).然后从获得的表中,我们将所有名称和值作为针对每个唯一 id 的单个值请参阅此处的说明 SQL Fiddle Demo(向下滚动有两个结果集)
Update Splitting in two steps. First we get a table having all values(comma separated) against a unique[Name,id]. Then from obtained table we get all names and values as a single value against each unique id See this explained here SQL Fiddle Demo (scroll down as it has two result sets)
编辑 阅读问题时出错,我仅按 id 分组.但是如果(值要按名称和 id 分组,然后按 id 分组),则需要两个 group_contacts.以前的答案是
Edit There was a mistake in reading question, I had grouped only by id. But two group_contacts are needed if (Values are to be concatenated grouped by Name and id and then over all by id). Previous answer was
select
id,group_concat(concat(`name`,':',`value`) separator ',')
as Result from mytbl group by id
你可以在这里看到它的实现:SQL Fiddle Demo
You can see it implemented here : SQL Fiddle Demo
这篇关于如何在 MySQL 的 CONCAT 中使用 GROUP_CONCAT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
如何有效地使用窗口函数根据 N 个先前值来决定How to use windowing functions efficiently to decide next N number of rows based on N number of previous values(如何有效地使用窗口函数根据
在“GROUP BY"中重用选择表达式的结果;条款reuse the result of a select expression in the quot;GROUP BYquot; clause?(在“GROUP BY中重用选择表达式的结果;条款?)
Pyspark DataFrameWriter jdbc 函数的 ignore 选项是忽略整Does ignore option of Pyspark DataFrameWriter jdbc function ignore entire transaction or just offending rows?(Pyspark DataFrameWriter jdbc 函数的 ig
使用 INSERT INTO table ON DUPLICATE KEY 时出错,使用 Error while using INSERT INTO table ON DUPLICATE KEY, using a for loop array(使用 INSERT INTO table ON DUPLICATE KEY 时出错,使用 for 循环数组
pyspark mysql jdbc load 调用 o23.load 时发生错误 没有合pyspark mysql jdbc load An error occurred while calling o23.load No suitable driver(pyspark mysql jdbc load 调用 o23.load 时发生错误 没有合适的
如何将 Apache Spark 与 MySQL 集成以将数据库表作为How to integrate Apache Spark with MySQL for reading database tables as a spark dataframe?(如何将 Apache Spark 与 MySQL 集成以将数据库表作为