交叉查询合并字段问题不知如何下手

风紫豪 2005-08-13 03:21:29
--表结构如下
create table tb(bus nvarchar(10),station nvarchar(50))
insert tb select '1路' ,'洪家坡'
union all select '1路','驷马桥'
union all select '1路' ,'南大街'
union all select '2路','荷花池'
union all select '2路' ,'高笋塘'
go

--最后查询结果
bus station
1路 洪家坡|驷马桥|南大街
2路 荷花池|高笋塘
...全文
140 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
inanition 2006-04-28
  • 打赏
  • 举报
回复
除了函数没别的办法办法了吗?函数的效率是最高的吗?
iwl 2005-08-13
  • 打赏
  • 举报
回复
就是最近的那个话题:
http://community.csdn.net/Expert/topic/4186/4186501.xml?temp=.6206324
一句比较复杂的SQL语句不知如何写?又有字符合并,又有数值相加!具体见内!
风紫豪 2005-08-13
  • 打赏
  • 举报
回复
太感谢了!
结贴。
tommysun 2005-08-13
  • 打赏
  • 举报
回复
樓上結果正確,但建議返回值定義晝大一點,以免長度不夠
declare @returnValue as varchar(30) =>
declare @returnValue as varchar(500)
子陌红尘 2005-08-13
  • 打赏
  • 举报
回复
create function f_str(@bus nvarchar(10))
returns nvarchar(4000)
as
begin
declare @ret nvarchar(4000)
set @ret = N''
select @ret = @ret + N'|'+station from tb where bus = @bus
set @ret = stuff(@ret,1,1,'')
return @ret
end
go


select bus,station=dbo.f_str(bus) from tb group by bus
zlp321002 2005-08-13
  • 打赏
  • 举报
回复
--写个函数就可以了!没看清楚是"|"连接的,修改下
--函数
ALTER function F_GetStr(@bus as varchar(10))
returns Varchar(30)
As
Begin
declare @returnValue as varchar(30)
set @returnValue =''
select @returnValue=@returnValue +'|'+rtrim(ltrim(station)) from
(select station from tb where bus=@bus) A

return stuff(@returnValue,1,1,'')
End

--查询
select bus,station=dbo.F_GetStr(bus) from tb
group by bus
--结果
bus station
---------- ------------------------------
1路 洪家坡|驷马桥|南大街
2路 荷花池|高笋塘

(所影响的行数为 2 行)
--删除测试环境
drop table TB
drop function F_GetStr
zlp321002 2005-08-13
  • 打赏
  • 举报
回复
--写个函数就可以了!
--测试环境
create table tb(bus nvarchar(10),station nvarchar(50))
insert tb select '1路' ,'洪家坡'
union all select '1路','驷马桥'
union all select '1路' ,'南大街'
union all select '2路','荷花池'
union all select '2路' ,'高笋塘'
go
--函数
Create function F_GetStr(@bus as varchar(10))
returns Varchar(30)
As
Begin
declare @returnValue as varchar(30)
set @returnValue =''
select @returnValue=@returnValue +','+rtrim(ltrim(station)) from
(select station from tb where bus=@bus) A

return stuff(@returnValue,1,1,'')
End

--查询
select bus,station=dbo.F_GetStr(bus) from tb
group by bus
--结果
bus station
---------- ------------------------------
1路 洪家坡,驷马桥,南大街
2路 荷花池,高笋塘

(所影响的行数为 2 行)
--删除测试环境
drop table TB
drop function F_GetStr

34,594

社区成员

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

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