如下表:AggregationTable
Id |
Name |
1 |
趙 |
2 |
錢 |
1 |
孫 |
1 |
李 |
2 |
周 |
如果想得到下圖的聚合結果
Id |
Name |
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
2.創建自定義字符串聚合函數
復制代碼代碼如下:
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
3.執行下面的語句,并查看結果
復制代碼代碼如下:
select dbo.AggregateString(Id),Id from AggregationTable
group by Id
結果為:
Id |
Name |
1 |
趙孫李 |
2 |
錢周 |