sql行转列

本文介绍在Sqlserver和Oracle中如何使用特定函数实现数据记录的聚合操作,包括使用Stuff函数去除多余字符及wm_concat函数实现列值连接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先是Sql server下的用法:

一个表结构如下: id name contetID
  1 test 1 
  2 test1 1
  3 test2 1 
  4 test3 2
  5 test4 2  
把它的记录加入另一个表中,结构如下:

  contetID names
  1 test,test1,test2
  2 test3,test4

 

if  OBJECT_ID( ' A ', ' U ') is  not  null  drop  table A
go
create  table A 
(
id  int, name  nvarchar( 10), contetID  int
)
go
insert  into A
select   1' test '1    union  all
select   2' test1 '1    union  all
select  3' test2 '1      union  all
select  4' test3 '2    union  all
select  5' test4 '2
go

select  distinct contetID,
name = stuff(( select  ' , ' +name  from A  as b  where a.contetID =b.contetID  for XML path( '')), 1, 1, ''
from A  as a
/*
contetID    name
----------- ----------------
1           test,test1,test2
2           test3,test4
*/

-- 将上面的结果直接插入另一张表中即可

insert  into othertb
select  distinct contetID,
name = stuff(( select  ' , ' +name  from A  as b  where a.contetID =b.contetID  for XML path( '')), 1, 1, ''
from A  as a

核心函数:

1. select ','+name  for XML path('') :产生,test,test1,test2。 for XML path本来是用来生产xml格式数据的,详情见下:

http://www.cnblogs.com/doubleliang/archive/2011/07/06/2098775.html

2. stuff

Stuff(expression1_Str,startIndex,lengthInt,expression2_Str)函数共有四个参数,其功能是将expression1_Str中自startIndex位置起删除lengthInt个字符,然后将expression2插入到expression1_Str中的startIndex位置。

在此处用于去除xml path产生的字串中第一个,号。

 

然后,在Oracle中,没有for xml path,但是提供了更方便的函数:

函数wm_concat(列名),该函数可以把列值以","号分隔起来,并显示成一行

http://blog.itpub.net/post/42245/522757

http://www.ningoo.net/html/2008/how_to_do_string_aggregate_on_oracle.html


 

 

转载于:https://www.cnblogs.com/calmzeal/archive/2011/11/10/2244723.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值