行变列 拼接字符串 MSSQL 一个超级搞的问题

由数据
ThreeLevelSortID KeyWordID   KeyWordName
2             142         key1
2             142         key2
3             143         key3
3             144         key4
得到数据大
ThreeLevelSortID KeyWordName
2                key1,key2
3                key3,key4
declare @tblTmp table (id int,ThreeLevelSortID int,KeyWordName nvarchar(max))
declare @tblTmpCount int
insert @tblTmp(id,ThreeLevelSortID)
select ROW_NUMBER() over (order by t.ThreeLevelSortID), t.ThreeLevelSortID 
from ( select Distinct ThreeLevelSortID from tbl_ThreeLevelSortKeyWordsDetail) t
select @tblTmpCount = count(1) from @tblTmp
declare @index int
set @index = 0
While(@index<)
begin
declare @currentThreeLevelSortID int
select @currentThreeLevelSortID = ThreeLevelSortID
from @tblTmp where id = @index
--拼接关键词字符串
declare @keywords nvarchar(max)
select @keywords=ISNULL(@keywords+';','')+k.KeyWordName from 
(SELECT h.KeyWordID,h.ThreeLevelSortID,j.KeyWordName FROM dbo.tbl_ThreeLevelSortKeyWordsDetail h,
dbo.tbl_KeyWords j
WHERE ThreeLevelSortID = @currentThreeLevelSortID
AND h.KeyWordID = j.KeyWordID) k
update @tblTmp set KeyWordName = @keywords 
where ThreeLevelSortID = @currentThreeLevelSortID
set @keywords = null
set @index = @index +1
end
select * from @tblTmp
求简单方法

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值