公司实施小姑娘要我写一个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
 

最新文章

  1. FreeRTOS和Ucos在打开关闭中断的区别
  2. 2016年湖南省第十二届大学生计算机程序设计竞赛---Parenthesis(线段树求区间最值)
  3. 网络初见&amp;网络监测
  4. ActiveMQ安装与使用
  5. js 与或运算符 || &amp;&amp; 妙用
  6. yii框架中应用jquery表单验证插件
  7. Dubbo服务调用的动态代理和负载均衡
  8. 研究一家公司 z
  9. iOS支付 IPAPayment demo iTunes Conection里面添加测试帐号,添加商品,实现购买过程
  10. select函数详解及应用
  11. POJ3771+Prim
  12. Linux 互斥锁的实现原理(pthread_mutex_t)
  13. Lambda表达式与函数式接口
  14. [UE4]UMG小结
  15. python 读写json文件(dump, load),以及对json格式的数据处理(dumps, loads)
  16. struts框架总结
  17. matplotlib基本使用(矩形图、饼图、热力图、3D图)
  18. [php]文件下载简述
  19. Ubuntu 修改IP地址
  20. 容器中跨主机的网络方案-Weave

热门文章

  1. bzoj 1875: [SDOI2009]HH去散步 -- 矩阵乘法
  2. gearman学习笔记
  3. PYQT窗口居中
  4. 华为S5300系列升级固件S5300SI-V100R003C00SPC301.cc
  5. 详解Google Chrome浏览器(操作篇)(上)
  6. 用最简单的例子理解模板方法模式(Template Method Pattern)
  7. andriod获得应用程序的Context
  8. JConsole详解
  9. Unix/Linux环境C编程新手教程(30) 字符串操作那些事儿
  10. Java操作Mongodb 保存/读取java对象到/从mongodb