IdName
1趙
2錢
1孫
1李
2周
如果想得到下圖的聚合結果
IdName
1趙孫李
2錢周
利用SUM、AVG、COUNT、COUNT(*)、MAX 和 MIN是無法做到的。因為這些都是對數值的聚合。不過我們可以通過自定義函數的方式來解決這個問題。
1.首先建立測試表,并插入測試數據:
復制代碼 代碼如下:
create table AggregationTable(Id int, [Name] varchar(10))
go
insert into AggregationTable
select 1,'趙' union all
select 2,'錢' union all
select 1,'孫' union all
select 1,'李' union all
select 2,'周'
go
復制代碼 代碼如下:
Create FUNCTION AggregateString
(
@Id int
)
RETURNS varchar(1024)
AS
BEGIN
declare @Str varchar(1024)
set @Str = ''
select @Str = @Str + [Name] from AggregationTable
where [Id] = @Id
return @Str
END
GO
復制代碼 代碼如下:
select dbo.AggregateString(Id),Id from AggregationTable
group by Id
結果為:
IdName
1趙孫李
2錢周
新聞熱點
疑難解答