Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何返回一行但连接原因列_Sql_Sql Server_Sql Server 2012_Grouping_Sql Server Group Concat - Fatal编程技术网

Sql 如何返回一行但连接原因列

Sql 如何返回一行但连接原因列,sql,sql-server,sql-server-2012,grouping,sql-server-group-concat,Sql,Sql Server,Sql Server 2012,Grouping,Sql Server Group Concat,我有一个sql server 2012数据库表,其中包含如下数据: id import_id tenancyname owner reason ----- ---------- ------------ ----- ------ 1 1 test null Owner is missing 2 2 null null Tenancy Name

我有一个sql server 2012数据库表,其中包含如下数据:

id    import_id    tenancyname    owner    reason
----- ----------   ------------   -----    ------
1      1            test          null     Owner is missing
2      2            null          null     Tenancy Name is Missing
2      2            null          null     Owner is Missing
从上面的数据可以看出,行id为2有两个原因,因为该行有两个问题

现在,我要做的是只返回一次行,但将原因连接到一个单元格中,使其如下所示:

id    import_id    tenancyname    owner    reason
----- ----------   ------------   -----    ------
1      1            test          null     Owner is missing
2      2            null          null     Tenancy Name is Missing \newline Owner is Missing
非常感谢专家们的帮助

尝试以下方法:

SELECT A.id, A.import_id, A.tenancyname, A.owner, MAX(STUFF(fxMerge.reason, 1, 1, '')) 
FROM tableA A
CROSS APPLY(
    SELECT ',' + reason 
    FROM tableA A1
    WHERE A.import_id = A1.import_id 
    FOR XML PATH('')
) fxMerge (reason) 
GROUP BY A.id, A.import_id, A.tenancyname, A.owner

这个问题有答案,但有一个“正确”的方法。有些答案是不完整的

你想要:

select id, import_id, tenancyname, owner,
       stuff((select '
' + reason
             from table t2
             where t2.id = t.id
             for xml path ('concat'), type
            ).value('/concat[1]', 'varchar(max)'),
            1, 1, '')
from table t
group by id, import_id, tenancyname, owner;

使用
value
提取值很重要,因为这解决了字符转换为xml等价物的问题(例如,
&;
而不是
&

SQL server是否支持GROUP\u CONCAT?如果是,请按id从tablename group中选择id、import\u id、tenancyname、owner、group\u concat(原因)、import\u id、tenancyname、owner检查此链接:查看一下。您的工作非常好,但如何在原因中添加换行符而不是逗号?当它进入excel时,原因在列表中