您的位置:首页 > 其它

经常遇到的,一个字段显示多字段数据!

2005-01-19 23:23 288 查看
原贴:http://community.csdn.net/Expert/topic/3721/3721293.xml?temp=.4743158
有表內容﹕
編號 內容
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解决方法:
http://community.csdn.net/Expert/topic/4323/4323684.xml?temp=.1937982
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐