sqlserver 查询时合并相同项

sqlserver 查询时合并相同项

一、例子

现在有一个临时表如下:

autoIDidnamedescriptiontime
132167542张三电脑2021-12-1
448978925李四手机2021-12-5
732167542张三A2021-12-8
1148978925李四B2021-12-15

查询时需要合并id和name相同的description,合并后数据取autoID最小的记录,即,效果如下:

autoIDidnamedescriptiontime
132167542张三电脑A2021-12-1
448978925李四手机B2021-12-5

二、建表

select * into #table
from (
	select 1 as autoID, '32167542' as id, '张三' as name, '电脑' as description, 2021-12-1 as time
	union
	select 4 as autoID, '48978925' as id, '李四' as name, '手机' as description, 2021-12-5 as time
	union
	select 7 as autoID, '32167542' as id, '张三' as name, 'A' as description, 2021-12-8 as time
	union
	select 11 as autoID, '48978925' as id, '李四' as name, 'B' as description, 2021-12-15 as time
)x

三、过程

  1. 根据id和name分组查询,使用for xml path合并description并将数据放入临时表中
IF OBJECT_ID('Tempdb.dbo.#tableDescription') IS NOT NULL DROP TABLE #tableDescription
select t1.id, t1.name
	,stuff((select '/' + description from #table t2
where t1.id = t2.id
	and t1.name = t2.name
	for xml path('')),1,1,'') as description  
into #tableDescription
from #table t1  
group by t1.id, t1.name
  1. 修改临时表#table的Description
update #table.description = #tableDescription.description
from #table
left join #tableDescription
on #table.id = #tableDescription.id
where #tableDescription.id is not null
  1. 根据id和name分组,取每组最前面的一行数据
IF OBJECT_ID('Tempdb.dbo.#autoMin') IS NOT NULL DROP TABLE #autoMin
select min(autoID) as autoID into #autoMin from #table group by id,name
  1. 联表,筛选出每组第一行的数据
select #table.* from #table
left join #autoMin on #table.autoID = #autoMin.autoID
where #autoMin.autoID is not null
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值