Sql Server 字串彙總函式_MsSql

來源:互聯網
上載者:User
如下表: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 錢周

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.