关于SQL 行转列的办法
公司实施小姑娘要我写一个SQL给她
需求如下:
现在有表A,字段 id code parentid backres,现数据如下
id code parentid backres
1 A 5
2 B 5
3 C 5
4 D 5
5 E 6
6 F
我想得到的是
id code parentid backres
1 A 5 B;C;D;
2 B 5 A;C;D;
3 C 5 A;B;D;
4 D 5 A;B;C;
5 E 6
6 F
意思是,根据Parentid得到ABCD都属于E,然后将ABCD的Backres改为,A;B;C;D;,减去它们本身
我做了一个很笨的办法 用游标遍历 再用参数存值 sql如下
create table #temp
(
Code nvarchar(50),
BackCode nvarchar(4000)
)
declare cursor1 cursor
for select Id,Code,parentid from Master_ResourceUnit where parentid is not null
open cursor1
DECLARE @Id nvarchar(100)
DECLARE @Code nvarchar(100)
DECLARE @Parentid nvarchar(100)
while @@FETCH_STATUS=0
begin
print @id
DECLARE @combinedString nvarchar(4000)
set @combinedString=''
select @combinedString=@combinedString+Code+';' from Master_ResourceUnit where ParentId =@Parentid and Code<>@code
insert #temp (Code,BackCode) values(@Code,@combinedString)
print @combinedString
fetch next from cursor1 into @id,@code,@Parentid
end
close cursor1
deallocate cursor1
效果是有的不过还是太笨了
结果她百度提问了 得到的解决办法如下:
--建表Create Table T( id int, code Varchar(10), parentid int, backres Varchar(10) ) --插入数据 insert into T values(1, 'A', 5,'') insert into T values(2, 'B', 5,'') insert into T values(3, 'C', 5,'') insert into T values(4, 'D', 5,'') insert into T values(5, 'E', 6,'') insert into T values(6, 'F', 0,'') --更新(按parentid把code按分号拼接,然后替换掉本身) Update T Set backres= Replace((Select code+';' From T A Where T.parentid=A.parentid For Xml Path('') ),code+';','') --查看结果 Select * from T用 For Xml Path('') 直接行转列了 这个相当强劲 固要记录一下子
转载百度知道链接 http://zhidao.baidu.com/question/1990438666470616867.html
浙公网安备 33010602011771号