我有一个T-SQL查询,它返回两行具有相同联系人姓名的结果但在其中一列中不同:
Contact Name BuildingID ClassID
------------------------------------
XXXX 720 3505
XXXX 720 3650
我需要将ClassID
两个值组合到ClassID
列中,如下所示:
Contact Name BuildingID ClassID
----------------------------------------
XXXX 720 3505;3650
答案 0 :(得分:0)
你可以尝试使用stuff和xml Path
SELECT ContactName, BuildingID,
STUFF((SELECT ','+CONVERT(varchar(20),classid) FROM Contacts where contactname= c.ContactName and BuildingId = c.BuildingID
FOR XML PATH('')),1,1,'') AS ClassId
FROM Contacts C
Group by ContactName, BuildingId
答案 1 :(得分:0)
SELECT *
FROM schema.table
WHERE src_id IN (
SELECT DISTINCT src_id
FROM schema.table
WHERE batch_id = ?
AND cand_source = 'mcp'
)
ORDER BY src_id,
match_score DESC
答案 2 :(得分:0)
如果您需要超过1次联系&建设,然后这应该工作:
select [Contact Name], BuildingId,
STUFF(
( SELECT concat(';',ClassId)
FROM YourTable t2
WHERE t1.[Contact Name] = t2.[Contact Name]
AND t1.BuildingId = t2.BuildingId
ORDER BY ClassId
FOR XML PATH('') , TYPE
).value('.', 'varchar(max)'),1,1,''
) as ClassIds
from YourTable t1
--where [Contact Name] = 'XXXX' and BuildingId = 720
group by [Contact Name], BuildingId;
并将它变成一个只有1家公司的变量&建筑?
这是一个小技巧:
declare @ClassIds varchar(max);
declare @ContactName varchar(30) = 'XXXX';
declare @BuildingId int = 720;
select @ClassIds = concat(@ClassIds+';',ClassId)
from YourTable
where [Contact Name] = @ContactName and BuildingId = @BuildingId
order by ClassId;
select @ContactName as [Contact Name], @BuildingId as BuildingId, @ClassIds as ClassIds;