SQl SerVer 数据库查询相同编号信息之间逗号串起来

这篇博客介绍如何在SQL Server中通过查询将属于同一班次的员工名字用逗号连接起来。首先,创建并删除必要的临时表,然后根据班次ID排序并更新员工表,使相同班次的员工名用顿号连接。接着,找到每个班次最长的员工名单,再与班次表关联,最后展示结果并删除临时表,确保不占用额外内存。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

正品水晶

 

有两张表T_Class (班次表)employee (员工所属班次表)

表中的数据如下图:

 

现在要求将早班、中班、晚班的员工查询出来用顿号隔开,效果如下图:

 

下面就是这个查询的代码供参考

 

-- 运行开始时先判断系统中是否存在对应的临时表,如果存在就删除(如果存在没有删除就运行则会报系统中已经存在***表)

if object_ID('tempdb.dbo.#employee') is not null   drop table #employee

if object_ID('tempdb.dbo.#employee_Max') is not null   drop table #employee_Max

if object_ID('tempdb.dbo.#employee_c') is not null   drop table #employee_c

 

--将员工表根据条件按班次字段排序存到一张临时表中

select * into #employee from dbo.employee order by t_id

 

declare @num int

declare @e_name varchar(8000) --这里建的变量类型必须和employee表的e_name类型一致且长度必须比姓名串起来后的字节要长

set @num=''

set @e_name=''

 

--更新临时表,将相同班次的的名称用逗号隔开

update #employee

set @e_name=e_Name=case when @num=t_id then e_Name+''+@e_Name else e_Name end,

    @num=t_id

 

--取相同班次名称字段最长的数据

select t_id,maxLeg=max(len(e_Name))

into #employee_Max

from #employee

group by t_id

 

--将得到的最长字段班次和串起来的临时表关联

select b.*

into #employee_c

from #employee_Max a join #employee b

on a.t_id=b.t_id

where a.maxLeg=LEN(b.e_Name)

 

select a.*,b.t_Name from #employee_c a join dbo.T_Class b

on a.t_id=b.t_id

 

--运行结束也要删除临时表,如果不删除临时表,临时表会一直在数据库服务器中占用内存,影响服务器速度。

 

 

正品水晶
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值