11月4号的随笔

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
有表內容﹕
編號 內容
A    abc
A    aaa
A    dddd
B    1223
B    fkdjfd
....

實現結果﹕
A   abc,aaa,dddd
B   1223,fkdjfd
要求用一條SQL實現﹐如﹕select sum(內容) from table group by 編號

--该问题,写一个合并函数,后,分组合并既可!

--测试数据
create Table 表(編號 varchar(20),內容 varchar(20))
insert 表 select 'A','abc'
union all select 'A','aaa'
union all select 'A','dddd'
union all select 'B','1223'
union all select 'B','fkdjfd'


--处理分组合并函数学
Create Function JoinStr(@SNO as varchar(20))
returns varchar(200)
begin
declare @s as varchar(8000)
set @s=''
select @s=@s+','+ltrim(rtrim(內容)) from
(
select 內容 from 表 where 編號=@SNO
)
A
set @s=stuff(@s,1,1,'')
return  @s
end

--查询语句
select 編號,dbo.JoinStr(編號) as 内容 from 表 group by 編號

--测试结果:
編號     内容
A abc,aaa,dddd
B 1223,fkdjfd

======用SQL解决方法:

table1: News
-----------------------------------------------------------
rsid     title     subject     class
1        天空蓝了  ....        小学文章
-----------------------------------------------------------


table2: ModifyLogs
-----------------------------------------------------------
rsid     NewsID    Name        Memo
1        1         张三        有一些错别字,还需要修改
2        1         张四        成语和一些词语用错
-----------------------------------------------------------

我现在需要用一条语名查询出这样的结果
-----------------------------------------------------------
Unid    Title        subject   Class        Name
1       天空蓝了     .....     小学文章     张三,张四

-----------------------------------------------------------
就是说把只要是修改了该文章的老师的名称显示在一个字段中.....
请问如何实现......


declare @tname varchar(4000)
set @tname=''
select @tname=@tname +rtrim(b.Name)+',' from ModifyLogs b left join News a on a.rsid=b.NewsID
set @tname=left(@tname,len(@tname)-1)
print @tname

select distinct a.rsid as Unida,a.Title,a.subject,a.Class,@tname as name from News a
left join ModifyLogs b on a.rsid=b.NewsID

posted on 2005-12-05 11:35  潘伟  阅读(203)  评论(0编辑  收藏  举报