sql 2005分组动态数据

时间:2010-09-27 22:34:33

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

我的数据看起来像这样

Investor    Contact
IBM           James  
IBM           Dean  
IBM           Sean  
Microsoft     Bill  
Microsoft     Steve

我需要数据看起来像这样

Investor     Contact
IBM          James,Dean,Sean  
Microsoft    Bill,Steve  

如果以上情况不可能<或者

Investor        Contact1  Contact2   Contact3  ...
IBM             James      Dean        Sean  
Microsoft        Bill      Steve

3 个答案:

答案 0 :(得分:3)

这应该有效:

SELECT Investor, 
STUFF((
    SELECT ',' + convert(nvarchar(50), Contact) 
    FROM Investors I2
    WHERE I2.Investor = I1.Investor
    FOR XML PATH('')
), 1, 1, '') Contacts
FROM Investors I1
GROUP BY Investor

导致:

IBM       James,Dean,Sean
Microsoft   Bill,Steve

答案 1 :(得分:2)

尝试使用以下方法获取逗号分隔列表。我将不得不更多地使用它来弄清楚如何让分组工作。

DECLARE @listStr VARCHAR(MAX)
SELECT @listStr = COALESCE(@listStr+',' , '') + Contact
FROM InvestorContact
SELECT @listStr

答案 2 :(得分:2)

以防您的任何联系人姓名中包含特殊的XML字符:the Tony Rogerson approach

;with data as
(
SELECT 'IBM' Investor,  'James' Contact UNION ALL  
SELECT 'IBM' ,          'Dean'  Contact UNION ALL  
SELECT 'IBM' ,          'Sean'  Contact UNION ALL  
SELECT 'Microsoft' ,    'Bill'  Contact UNION ALL    
SELECT 'Microsoft',     'Steve' Contact
)
SELECT Investor, 
   stuff((SELECT mydata
   FROM (
      SELECT ',' + Contact  AS [data()]
      FROM
      data AS d2
      WHERE d2.Investor = d1.Investor
      FOR XML PATH(''), TYPE
   ) AS d ( mydata ) FOR XML RAW, TYPE ).value( '/row[1]/mydata[1]', 'varchar(max)' )
, 1, 1, '')
FROM data d1
GROUP BY Investor