Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

sql - Combining rows of queried results by unique identifier?

I have a query that searches through several tables and returns one row for every value in one specific column of one of the queried tables. The table returns multiple rows for one unique identifier. What I want to do is combine those rows that have the same unique identifier and combine 2 of the column's value separated by commas and return those values as a unique column.

Example:

 Museum     MuseumID     Country     City     Paintings     Sculptures

 Louvre     345          France      Paris    Mona Lisa     NULL
 Louvre     345          France      Paris    NULL          Venus De Milo
 Louvre     345          France      Paris    Ship of Fools NULL

Instead I would like to make the query do this:

 Museum     MuseumID     Country     City     Art
 Louvre     345          France      Paris    Mona Lisa, Venus De Milo, Ship of Fools

I need to turn this query into a stored procedure that can be used in a C# program. At first I just took the data as is and used C# to combine the rows using arrays and some logic but I HAVE TO make this a stored procedure instead to make the data come over to the C# program already sorted and combined. I don't want to I have to. I need help.

Can anyone help with this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...