Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Combinare righe di risultati interrogati per identificatore univoco?

DECLARE @a TABLE
(
    Museum VARCHAR(32),
    MuseumID INT, 
    Country VARCHAR(32),
    City VARCHAR(32),
    Paintings VARCHAR(32),
    Sculptures VARCHAR(32)
);

INSERT @a VALUES
('Louvre',345,'France','Paris', 'Mona Lisa',     NULL),
('Louvre',345,'France','Paris', NULL,            'Venus De Milo'),
('Louvre',345,'France','Paris', 'Ship of Fools', NULL);


SELECT DISTINCT Museum, MuseumID, Country, City, 
    Art = STUFF((SELECT ', ' + COALESCE(Paintings, Sculptures, '')
    FROM @a AS a2
    WHERE a2.museum = a.museum AND a2.MuseumID = a.MuseumID
    AND a2.Country = a.Country AND a2.City = a.City
    FOR XML PATH(''), TYPE).value('.[1]', 'nvarchar(max)'),
    1,2,'')
FROM @a AS a;