如何实现,下查询。。

ga3ga3 2004-10-27 07:14:17
table1
t1id f1
1 i1
2 i2

table2
t2id t1id d1
1 1 你
2 1 你1
3 2 你2
4 2 你3
5 2 你4

如何查询出这样的结果:
t1id d3
1 你,你1
2 你2,你3,你4
...全文
146 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
qizhanfeng 2004-10-28
  • 打赏
  • 举报
回复
不用函数这样

create table table1(tlid int,f1 varchar(20))
insert into table1 select 1,'i1'
union select 2,'i2'

create table table2(t2id int,tlid int,d1 varchar(20))
insert into table2 select 1, 1, '你'
union select 2, 1, '你1'
union select 3, 2, '你2'
union select 4, 2, '你3'
union select 5, 2, '你4'


create proc p_t
as
begin
declare @t int,@d1 varchar(20)
select tlid,d1 as d3 into #t from table2 order by tlid,d1
update #t set d3=case when tlid=@t then @d1 else d3 end,@d1=case when tlid=@t then @d1+','+d3 else d3 end,@t=tlid
select tlid,max(d3) d3 from #t group by tlid
end

exec p_t
--结果
tlid d3
----------- --------------------
1 你,你1
2 你2,你3,你4

(所影响的行数为 2 行)
zheninchangjiang 2004-10-28
  • 打赏
  • 举报
回复
或者写个函数:
create function f_merg(@tlid varchar(100))
returns varchar(1000)
as
begin
declare @r varchar(1000)
set @r=''
select @r=@r+','+d1 from table2 where tlid=@tlid
set @r=stuff(@r,1,1,'')
return(@r)
end
go

select tlid,d3=dbo.f_merg(tlid) from table2 group by tlid
lsxaa 2004-10-28
  • 打赏
  • 举报
回复
create function c_str(@t1id)
returns varchar(8000)
as
begin
declare @s varchar(8000)
set @s=''
select @s=@s+','+fmc from table2 where t1id=@t1id
return stuff(@s,1,1,'')
end

select t1id,dbo.c_str(t1id) from table2 group by t1id
zheninchangjiang 2004-10-28
  • 打赏
  • 举报
回复
手工写入
ga3ga3 2004-10-28
  • 打赏
  • 举报
回复
谢谢
但这个太繁琐了。。有简单的嘛?
victorycyz 2004-10-27
  • 打赏
  • 举报
回复
http://community.csdn.net/Expert/topic/3245/3245226.xml?temp=.5957147

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧