在表Cityid和CITYname 2列中:
city id city name
1 Bang
1 hyd
1 pune
2 hyd
2 pune
2 chennai
我想要结果:
1 ---hyd,pune,bang(all citynames of city id)
2---
答案 0 :(得分:1)
您遗漏了回答问题所需的一些重要细节:您使用的是哪种语言?
如果您在SQL Server 2005/2008上使用T-SQL,那么这就是答案:
你的表:
CREATE TABLE [dbo].[cities](
[cityid] [int] NULL,
[cityname] [varchar](50) NULL
) ON [PRIMARY]
您的数据:
insert into cities(cityid,cityname)values(1,'Seattle')
insert into cities(cityid,cityname)values(1,'Portland')
insert into cities(cityid,cityname)values(2,'New York')
insert into cities(cityid,cityname)values(2,'Newark')
您的查询:
declare @result table(
cityid int,
cityname varchar(max)
)
declare @queue table(
cityid int,
cityname varchar(50)
)
declare @cityid int
declare @cityname varchar(50)
insert into @queue select * from cities
while(exists(select top 1 cityid from @queue)) begin
select top 1 @cityid = cityid, @cityname = cityname from @queue
if(exists(select cityid from @result where cityid = @cityid)) begin
update @result
set cityname = cityname + ', ' + @cityname
where cityid = @cityid
end else begin
insert into @result(cityid,cityname) values(@cityid,@cityname)
end
delete from @queue where cityid = @cityid and cityname = @cityname
end
select * from @result
你的结果:
cityid cityname
1 1 Seattle, Portland
2 2 New York, Newark
答案 1 :(得分:0)
查找GROUP_CONCAT
或USER DEFINED AGGREGATE FUNCTIONS