mysql中的group_concat函数的功能
将group by产生的同一个分组中的值连接起来,返回一个字符串结果。
group_concat函数首先根据group by指定的列进行分组,将同一组的列显示出来,并且用分隔符分隔。由函数参数(字段名)
select group_concat(emp_name) from emp;
语法:group_concat([distinct] 字段名 [order by 排序字段 asc/desc] [separator ‘分隔符’])
(1)使用distinct可以排除重复值;
(2)如果需要对结果中的值进行排序,可以使用order by子句;
(3)separator是一个字符串值,默认为逗号。
实例:
1:以id分组,把name字段的值在同一行打印出来,逗号分隔(默认):
select id, group_concat(name) from student group by id;
2:自定义分隔[分号]
select id,group_concat(name separator ‘;’) from student group by id;
实例
Select
Id,
STUFF(
(
SELECT ‘,’ + T.Name
FROM #student T
WHERE A.Id= T.Id
FOR XML PATH(‘’)
), 1, 1, ‘’
) as group_concat
FROM #student A
Group by Id
实践:
select Convert(char(10),g.SettleTime,120) as settelTime, g.Platform,g.UserId,SUM(AvailableBetAmount) as validAmount,STUFF(
(
select ',' + a.orderId from G_Game_Order as a
where a.UserId = g.userId and a.Platform=g.Platform and Convert(char(10),a.SettleTime,120)=Convert(char(10),g.SettleTime,120) FOR XML PATH('')
),1,1,''
) as orderId
from G_Game_Order g,C_User_Register u where u.UserId=g.UserId and g.status=1 and g.XmState=0
and g.SettleTime>='2023-08-01'
group by g.Platform,g.UserId,Convert(char(10),g.SettleTime,120)