我有以下[表格a]
id result
1 a
1 b
1 b
1 c
2 e
2 e
2 e
2 f
我在执行group_concat后得到以下内容
select id , Group_Concat(result) from [table a]
group by id
id result
1 a,b,b,c
2 e,e,e,f
但我想在结果集中的值之前显示值的次数,以避免冗余,如下所示
id result
1 a,2 b,c
2 3 e,f
我怎样才能实现它?
答案 0 :(得分:2)
按ID和结果分组以获得计数。然后按ID分组以构建字符串。
select
id,
group_concat(case when cnt = 1 then result else concat(cnt, ' ', result) end) as results
from
(
select id, result, count(*)
from mytable
group by id, result
) t
group by id;