如何在MSSQL上使用GROUP_CONCAT函数

时间:2017-10-10 08:00:38

标签: sql-server

如何在MySQL运行时在MSSQL上使用GROUP_CONCAT函数?

current table;
     QUESTION_ID    ANSWER_ID   USER
1.        1             1       A
2.        1             1       B
3.        1             2       C

i need;

     QUESTION_ID    ANSWER_ID   USER
1.        1             1       A, B
2.        1             2       C

提前感谢..

2 个答案:

答案 0 :(得分:2)

我认为等效功能可能是STRING_AGG。 (SQL Server 2017及更高版本)

select QUESTION_ID, ANSWER_ID, STRING_AGG(USER, ', ') as USER
from t1
group by QUESTION_ID, ANSWER_ID

https://docs.microsoft.com/es-es/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-2017

答案 1 :(得分:0)

尝试:

select distinct t1.QUESTION_ID, t1.ANSWER_ID
  STUFF((SELECT distinct '' + t2.USER
         from yourtable t2
         where t1.ANSWER_ID= t2.ANSWER_ID
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,0,'') data
from yourtable t1;