如何在单列中选择3行值

时间:2016-11-02 12:52:33

标签: sql-server

我在SQL Server中有一个表:

M_AllParty_HDR(ID, PartyName, AgentId, IsDeleted, IsActive)

我想在单行中选择任何特定AgentID的所有PartyName,并且PartyName应该用逗号符号区分。我已经完成了以下问题来解决这个问题

select PartyName+',' 
from M_AllParty_HDR 
where AgentID=1613 and IsDeleted=0 and IsActive=1

输出结束

Rajesh mishra
Siddhi traders
Kamat tiwari

这是3行。 但我想要输出如下: -

Rajesh mishra,Siddhi traders,Kamat tiwari

怎么可能?请帮助我一个人。

3 个答案:

答案 0 :(得分:1)

使用SQL-Server时,通常使用以下事实来完成:没有元素名称的XML将连接文本

select stuff(
(
select ',' + PartyName
from M_AllParty_HDR 
where AgentID=1613 and IsDeleted=0 and IsActive=1
for xml path('')
),1,1,'');

STUFF会删除前导,

如果您的PartyNames中可能有禁用字符(尤其是<, > or &),您可以使用此字符:

select stuff(
((
select ',' + PartyName
from M_AllParty_HDR 
where AgentID=1613 and IsDeleted=0 and IsActive=1
for xml path(''),TYPE).value('.','nvarchar(max)')
),1,1,'');

(未经测试...)

答案 1 :(得分:0)

您可以尝试这样

SELECT
    p.agentid,
    STUFF((SELECT
        ',' + PartyName
    FROM M_AllParty_Hdr
    WHERE agentid = p.agentid
    FOR xml PATH ('')), 1, 1, '') AS CommaSeperated
FROM M_AllParty_Hdr p
WHERE agentid = 1613 AND IsDeleted = 0 AND IsActive = 1
GROUP BY p.agentid

答案 2 :(得分:0)

方法1:最简单的方法

DECLARE @Names VARCHAR(8000) 
SELECT @Names = COALESCE(@Names + ', ', '') + PartyName 
FROM M_AllParty_HDR
WHERE PartyName IS NOT NULL and AgentID=1613 and IsDeleted=0 and IsActive=1
print @Names

方法2:获得更好的效果。

SELECT STUFF((SELECT PartyName +','
    FROM M_AllParty_HDR WHERE PartyName IS NOT NULL and AgentID=1613 and IsDeleted=0 and IsActive=1
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')