[英]MySQL: one column/multiple rows group_concat into multiple columns filled with values from another column
I've seen many answers to group_concat one column/multiple rows into multiple columns, but I cannot find how you populate the new columns with data from a second column.我已经看到许多关于 group_concat 一列/多行到多列的答案,但我找不到如何用第二列的数据填充新列。
My table of data looks like this:我的数据表如下所示:
first_name doc_number doc_status
a 1 new
a 2 new
b 3 pending
b 4 approved
c 5 new
c 6 approved
c 7 approved
This is the result I would like:这是我想要的结果:
first_name doc_status_new doc_status_pending doc_status_approved
a 1,2
b 3 4
c 5 6,7
This is the result I get:这是我得到的结果:
first_name doc_status_new doc_status_pending doc_status_approved
a 1,2
b 3,4
c 5,6,7
Row 2 shouldn't have '3,4' in the same column.第 2 行不应在同一列中包含“3,4”。 And Row 3 shouldn't have "5,6,7" in the same column either.
第 3 行也不应该在同一列中包含“5,6,7”。 I do not know how to get group_concat to only list the doc_number that is relevant to that 'where' statement only.
我不知道如何让 group_concat 只列出与“where”语句相关的 doc_number。
This is the code I've used:这是我使用的代码:
select
first_name,
case when doc_status = 'new' then group_concat(doc_number) end as doc_status_new,
case when doc_status = 'pending' then group_concat(doc_number) end as doc_status_pending,
case when doc_status = 'approved' then group_concat(doc_number) end as doc_status_approved
from table_name
group by first_name;
You probably need -你可能需要——
select first_name,
group_concat(case when doc_status = 'new' then doc_number end) as doc_status_new,
group_concat(case when doc_status = 'pending' then doc_number end) as doc_status_pending,
group_concat(case when doc_status = 'approved' then doc_number end) as doc_status_approved
from table_name
group by first_name;
I think the better solution is using UNION, it is very fast, and using LIKE:我认为更好的解决方案是使用 UNION,它非常快,并且使用 LIKE:
(SELECT group_concat(doc_number) AS doc_status_new WHERE doc_status LIKE 'new')
UNION
(SELECT group_concat(doc_number) AS doc_status_pending WHERE doc_status LIKE 'pending')
UNION
(SELECT group_concat(doc_number) AS doc_status_approved WHERE doc_status LIKE 'approved')
I hope this help.我希望这会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.