开发者

SQL Server 2005 - Rows to Cols

I have a table CSFT_SuggestionItem with cols like:

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

For each SuggestionItem, there can by multiple "Applications" where it can be associated, so I have CSFT_SuggestionItemApplication

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

And I have an CSFT_Application Table

ApplicationID        Description
----------------------------------
1                    Spring
2                开发者_StackOverflow    Summer
3                    Fall
4                    Winter

I want my output to look like this:

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

I know I can do this by Looping. But, is there a better way in Sql server 2005? Maybe COALESCE, PIVOT, etc.


Use:

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

Alternate using 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜