当另一列重复时连接列

时间:2018-07-25 03:50:04

标签: tsql sql-server-2012

enter image description here

如何使表格看起来像下面那样变成串联形式

1844|a 
1847|a,b
1848|34,qaz

1 个答案:

答案 0 :(得分:1)

Good day,

This question was asked with the tag "sql-server-2012", but I can't feel good to give the answer without first show how simple it is to solve these type of questions with new function STRING_AGG that was added to SQL Server 2017.

Therefore, First I will add the code for the sample DDL+DML (create the relevant table and insert sample data), which is something that the person who ask the question must ad to the question, but was not added here

Secondly I will show the solution in SQL Server 2017 and above

And finally I will give the solution for older versions like SQL Server 2012

Have fun, and I recommend to read all

DDL + DML

NOTE! Instead of posting images and stories on your table, it is always better to present us a simple way to reproduce the issue! This means that when you have question related to queries, then you should provide us with queries to create a sample table (including the indexes) and to insert sample data. In addition you should add the requested result, which was provided here.

/*************************** DDL+DML */

drop table if exists T; -- this work only from SQL Server 2016
create table T(id int, txt nvarchar(10))
GO

INSERT T(id,txt) 
values (1844,'a'),(1847,'a'),(1847,'b'),(1848,'34'),(1848,'q')
GO

Select * from T
GO

Solution for SQL Server 2017 and above

/*************************** Solution */
-- New from 2016: STRING_SPLIT ( string , separator )  
-- New from 2017: STRING_AGG ( expression, separator ) [ <order_clause> ]
SELECT id,STRING_AGG(ISNULL(txt,''), ',') WITHIN GROUP (order by id)
from T
group by id
GO

Solution for old versions of SQL Server

This solution was taken from this blog: http://ariely.info/Blog/tabid/83/EntryId/152/Unsplit-Using-For-XML-with-group-by-columns.aspx

SELECT
    id,
    STUFF(
        (
            SELECT ',' + t_in.txt
            FROM T t_in
            WHERE (t_in.id  = t_out.id)
            FOR XML PATH ('')
        ),1,1,''
    ) AS NameValues
FROM T t_out
GROUP BY id
GO

I hope that this solve the question ;-)