将多个结果组合在一个列中

时间:2017-06-15 03:10:42

标签: sql-server

我有2个表,称为请求和请求关系,详情如下。

请求

reqId  regNum desc 
12     111    Tomato
13     112    Carrot
14     113    Chilli
15     114    Onion
16     115    Garlic

requestRelationship

reqID   relatedRequestId
12      14 
12      16
13      14
13      15

我希望显示如下信息

reqId  regNum desc    relateRequest
12     111    Tomato  113,115
13     112    Carrot  113,114 

目前我只有基本查询

select r.reqId, r.reqNum, r.desc, relateRequest = STUFF((select Distinct ', ' + regNum from request b where b.reqId = a.reqId FOR XML PATH (' ')), 1, 2, '')
from request r
INNER JOIN requestRelationship t WITH (NOLOCK) on r.reqID = t.reqID
order by r.reqId desc

1 个答案:

答案 0 :(得分:1)

您的STUFF基本上需要加入request上的relatedrequestid表(而您的外部查询正在加入reqID),因此您的整个选择应该看起来像这样:

SELECT DISTINCT R.reqID, R.regNum, R.[desc],
       relateRequest = STUFF(
            (SELECT DISTINCT ', ' + CAST(R2.regNum AS VARCHAR(10)) 
            FROM request AS R2 
            JOIN requestRelationship AS RR2 
                ON RR2.relatedrequestid = R2.reqID
            WHERE RR2.ReqID = RR.ReqID -- This joins to your outer query. -- You can also join on R.ReqID, doesn't make a difference.
            FOR XML PATH ('')), 1, 2, '')
FROM request AS R
JOIN requestRelationship AS RR
    ON RR.reqID = R.reqID;