SQL Server 2005 - 行到Cols

时间:2010-08-24 20:33:18

标签: sql sql-server sql-server-2005 tsql

我有一个表CSFT_SuggestionItem,其中包含cols:

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

对于每个SuggestionItem,可以通过多个“Applications”关联它,所以我有CSFT_SuggestionItemApplication

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

我有一个CSFT_Application表

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

我希望我的输出看起来像这样:

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

我知道我可以通过循环来做到这一点。但是,在Sql server 2005中有更好的方法吗?也许是COALESCE,PIVOT等。

1 个答案:

答案 0 :(得分:1)

使用:

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

使用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