-3

在表 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---
4

2 回答 2

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
于 2012-04-13T14:28:46.603 回答
0

查找 GROUP_CONCAT

或用户定义的聚合函数

于 2012-04-13T14:12:28.437 回答