我想将列转换为以逗号分隔的单行。
当前表:
main_cat | sub_cat |
--------------------
main 1 | sub 1 |
main 1 | sub 2 |
main 2 | sub 2 |
main 2 | sub 3 |
main 3 | sub 1 |
预期表
group_main | main 1 | main 2 | main 3 |
-------------------------------------------------------------
main 1, main 2, main 3 | sub 1, sub 2 |sub 2, sub 3|sub 1 |
我尝试GROUP_CONCAT
但未获得准确的输出
答案 0 :(得分:1)
您可以使用条件聚合:
select group_concat(distinct main_cat order by main_cat) as group_main,
group_concat(case when main_cat = 'main 1' then sub_cat end order by sub_cat) as main_1,
group_concat(case when main_cat = 'main 2' then sub_cat end order by sub_cat) as main_2,
group_concat(case when main_cat = 'main 3' then sub_cat end order by sub_cat) as main_3
from t;