
有两张表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
--运行结束也要删除临时表,如果不删除临时表,临时表会一直在数据库服务器中占用内存,影响服务器速度。
正品水晶
