2015-05-14 59 views

回答

1

你需要一個動態透視

IF(OBJECT_ID('YourTable','U') IS NOT NULL) 
    DROP TABLE YourTable 
CREATE TABLE YourTable (Name VARCHAR(100), VALUE INT) 
INSERT INTO YourTable VALUES 
('A', 25), 
('B', 30), 
('A', 35), 
('B', 40), 
('A', 45) 

DECLARE @Columns VARCHAR(1000), @ColumnAs VARCHAR(4000),@sql NVARCHAR(MAX) 


SELECT @Columns = STUFF((SELECT ',' + '[' + CONVERT(VARCHAR(30), number, 121) + ']' 
         FROM master..spt_values N 
         WHERE n.number BETWEEN 1 AND (SELECT TOP 1 COUNT(*) 
                 FROM YourTable 
                 GROUP BY Name 
                 ORDER BY COUNT(*) DESC) 
           AND TYPE = 'P' 
         FOR XML PATH('')), 1, 1, '') 

SELECT @ColumnAs = REPLACE(@Columns,'],[','] as [Value],[') + 'as [Value]' 

SET @sql = 'select [Name],' + @ColumnAs +' 
from 
(
    select *,ROW_NUMBER() over(PARTITION by Name order by value) as [rn] from YourTable 
) tab pivot 
(
    max([Value]) 
    for rn in(' + @Columns +') 
) as pvt' 

EXEC SP_EXECUTESQL @sql 
+0

我希望的是一個在線查詢,但感謝。乾杯。 –

+0

這件事不能在一行中完成:)。 –