【Transact-SQL】通过递归来实现:将多条记录的某个字段的值,用斜杠拼接在一起
2011-11-19 10:14
501 查看
需要把表@tt中的idd相同的记录中tchar字段的内容拼接在一起,结果如下
1,'abc/xyz/ggg'
2,'111/soft'
实验代码如下:
declare @tt table(idd int,tchar varchar(10))
insert into @tt
select 1,'abc' union all
select 1,'xyz' union all
select 1,'ggg' union all
select 2,'111' union all
select 2,'soft'
;with c
as
(
select idd,
tchar,
row_number() over(partition by idd order by tchar) as row
from @tt
),
cc --递归CTE
as
(
select idd,
cast(tchar as varchar(1000)) as ch,
row
from c
where row = 1
union all
select cc.idd,
ch=cast(cc.ch+'/'+c.tchar as varchar(1000)),
c.row
from cc
inner join c
on c.idd = cc.idd
and c.row = cc.row+1
),
ccc
as
(
select idd,ch,row,
row_number() over(partition by idd order by row desc) as rownum
from cc
)
select * from ccc
where rownum=1
/*
idd ch row rownum
1 abc/ggg/xyz 3 1
2 111/soft 2 1
*/
1,'abc/xyz/ggg'
2,'111/soft'
实验代码如下:
declare @tt table(idd int,tchar varchar(10))
insert into @tt
select 1,'abc' union all
select 1,'xyz' union all
select 1,'ggg' union all
select 2,'111' union all
select 2,'soft'
;with c
as
(
select idd,
tchar,
row_number() over(partition by idd order by tchar) as row
from @tt
),
cc --递归CTE
as
(
select idd,
cast(tchar as varchar(1000)) as ch,
row
from c
where row = 1
union all
select cc.idd,
ch=cast(cc.ch+'/'+c.tchar as varchar(1000)),
c.row
from cc
inner join c
on c.idd = cc.idd
and c.row = cc.row+1
),
ccc
as
(
select idd,ch,row,
row_number() over(partition by idd order by row desc) as rownum
from cc
)
select * from ccc
where rownum=1
/*
idd ch row rownum
1 abc/ggg/xyz 3 1
2 111/soft 2 1
*/
相关文章推荐
- 【Transact-SQL】通过递归来实现:将多条记录的某个字段的值,用斜杠拼接在一起
- oracle―SQL技巧之(二)WMSYS.WM_CONCAT函数实现多行记录用逗号拼接在一起
- oracle―SQL技巧之(二)WMSYS.WM_CONCAT函数实现多行记录用逗号拼接在一起
- 循环SQL语句实现,将一个数字字段的商数拆分成多条记录
- 实现有相同字段的不同记录中不同字段的拼接
- [通过制定SQL计划和系统计划实现]SQL Server 2005数据库定期备份和删除历史备份记录
- SQL 数据库 学习 007 通过一个示例简单介绍什么是字段、属性、列、元组、记录、表、主键、外键
- SQL语句实现在原字段后拼接字符串
- 行转列一个好玩的SQL(列数会视记录数变动,实现系统自定义字段功能)
- 有订单表SO_Table,单号字段RefNo VARCHAR(10),需要实现自动编号,格式为YYYYMMXXXX,其中XXXX为序号,如:2004050001,2004050002……2004059999等,采用Transact-SQL实现新订单编号的思
- 通过制定SQL计划和系统计划实现]SQL Server 2005数据库定期备份和删除历史备份记录
- 何用sql语句实现:将insert语句作为一个字段,插入到表格的一条记录之中
- SQL 拼接多个字段的值&一个字段多条记录的拼接
- 通过PL/SQL创建序列和触发器实现表自增字段
- SQL通过拆分某字段中的内容来实现与对应表连接查询
- 根据某个字段将多条记录的某个字段拼接成一个字段(SQL查询)
- *SelectOne SqlDataReader 通过SqlDataReader实现一条记录的读取*
- php 通过file_put_contents 实现记录sql语句
- SQL 拼接多个字段的值&一个字段多条记录的拼接
- 在asp.net中强烈建议通过参数来实现sql而不是sql拼接