2 Stimmen

SQL Server 2005 - Zeilen zu Spalten

Ich habe eine Tabelle CSFT_SuggestionItem mit Spalten wie:

SuggestionItemID  Title                Description, etc. 
------------------------------------------------------------
1                 Item 1               Do more work
2                 Item 2               I think more is good

Für jedes SuggestionItem kann es mehrere "Anwendungen" geben, mit denen es verknüpft werden kann, also habe ich CSFT_SuggestionItemApplication

SuggestionItemID    ApplicationID
----------------------------------
1                    1
1                    2
2                    1

Und ich habe eine CSFT_Application Tabelle

ApplicationID        Description
----------------------------------
1                    Spring
2                    Summer
3                    Fall
4                    Winter

Ich möchte, dass meine Ausgabe wie folgt aussieht:

SuggestionItemID     Applications
----------------------------------
1                    Spring, Summer  
2                    Spring

Ich weiß, dass ich das mit Looping machen kann. Aber, gibt es einen besseren Weg in Sql Server 2005? Vielleicht COALESCE, PIVOT, etc.

1voto

OMG Ponies Punkte 312816

Verwendung:

SELECT DISTINCT
       sia.SuggestionItemID,
       STUFF((SELECT ','+ a.description
                FROM CSFT_Application a
                JOIN CSFT_SuggestionItemApplication b ON b.applicationid = a.applicationid
               WHERE b.suggestionitemid = sia.suggestionitemid
            GROUP BY a.description
             FOR XML PATH('')), 1, 1, '') AS applications
  FROM CSFT_SuggestionItemApplication sia

Abwechselnd verwenden GROUP BY :

  SELECT sia.SuggestionItemID,
         STUFF((SELECT ','+ a.description
                  FROM CSFT_Application a
                  JOIN CSFT_SuggestionItemApplication b ON b.applicationid = a.applicationid
                 WHERE b.suggestionitemid = sia.suggestionitemid
              GROUP BY a.description
               FOR XML PATH('')), 1, 1, '') AS applications
    FROM CSFT_SuggestionItemApplication sia
GROUP BY sia.SuggestionItemID

CodeJaeger.com

CodeJaeger ist eine Gemeinschaft für Programmierer, die täglich Hilfe erhalten..
Wir haben viele Inhalte, und Sie können auch Ihre eigenen Fragen stellen oder die Fragen anderer Leute lösen.

Powered by:

X