如何将所有行合并为一个

时间:2014-07-24 16:11:03

标签: sql sql-server

USE oB 

--Consent for release of Insurance Information--
SELECT 
    a.objectID,
    LTRIM(RTRIM(a.attr1397)) 'LastName',
    LTRIM(RTRIM(a.attr1395)) 'FirstName',
    LTRIM(RTRIM(a.attr1400)) 'ID',
    LTRIM(RTRIM(b.attr1624)) 'Car Name',
    LTRIM(RTRIM(b.attr1626)) 'Pol Number'
FROM 
    dbo.nstance1029 a 
LEFT OUTER JOIN 
    dbo.nstance1048 b ON a.objectid = b.fk16

产生这个:

enter image description here

如何修改查询,以便每个a.objectID/LastName/FirstName/ID The Car Name/Pol Name出现在同一行而不是多行?

2 个答案:

答案 0 :(得分:1)

根据输出,您有一些数据具有相同的ID,LastName,Firstname,ID但Car Name和Pol Number不是。您可以添加DISTINCT和/或GROUP BY,但由于Pol编号和名称不同,您仍会有多行ObjectID,LN,FN,ID

答案 1 :(得分:1)

交叉申请将是这样的事情:

SELECT 
        a.objectID,
        LTRIM(RTRIM(a.attr1397)) 'LastName',
        LTRIM(RTRIM(a.attr1395)) 'FirstName',
        LTRIM(RTRIM(a.attr1400)) 'ID',
        temp.cars 'Car Name',
        temp.PolNumber 'Pol Number'
    FROM 
        dbo.nstance1029 a 
    CROSS APPLY (
        SELECT LTRIM(RTRIM(b.attr1624))  + ','
        FROM nstance1048  AS b
        WHERE a.objectid  = b.fk16  
        FOR XML PATH('')) 
        temp(cars)
    CROSS APPLY (
        SELECT LTRIM(RTRIM(b.attr1626)) + ','
        FROM nstance1048 AS b
        WHERE a.objectid =  b.fk16
        FOR XML PATH('')) 
        temp(PolNumber)