用于组合表的同一列中的数据的SQL查询

时间:2022-12-03 00:14:50

I have a table (tblCity) with State name and city name as columns.

我有一个表(tblCity),其中州名和城市名称为列。

I have a requirement to show on screen State name and city names (all cities of a state as csv).

我要求在屏幕上显示州名和城市名称(州的所有城市为csv)。

I created a table variable, iterated through my tblCity table for every state and accomplished this.

我创建了一个表变量,通过我的tblCity表迭代每个状态并完成了这个。

However I would like to know if there is any easy way around.

但是我想知道是否有任何简单的方法。

1 个解决方案

#1


you can use coalesce to do that.

你可以使用coalesce来做到这一点。

Declare @city varchar(Max)
Set @city=''
Select @city=@city + Coalesce([City]+ ', ','') from tblCity
Select Left(@city,LEN(@city)-1) as [City]
GO

#1


you can use coalesce to do that.

你可以使用coalesce来做到这一点。

Declare @city varchar(Max)
Set @city=''
Select @city=@city + Coalesce([City]+ ', ','') from tblCity
Select Left(@city,LEN(@city)-1) as [City]
GO