开发者

How do i transform rows into columns in sql server 2005

There is a question here in stackoverflow with the same title but that is not what I am looking for.

I have a table like the one below

Name   | Count  
----------------    
Chery  | 257  
Drew   | 1500
Morgon | 13  
Kath   | 500  
Kirk   | 200  
Matt   | 76 

I need to trasform this result set into something like this

Chery | Drew | Morgon | Kath | Kirk | Matt  
-------------------------------------------  
257     1500     13      500    200    76

How do i acheive this usi开发者_StackOverflowng sql server 2005?


There are similar questions here,here answered in stackoverflow.

You need to use the operator PIVOT in your query to acheive this.Here is the example and explanation on how you can do that.The example is referenced from this source.

---I assumed your tablename as TESTTABLE---
DECLARE @cols NVARCHAR(2000)
DECLARE @query NVARCHAR(4000)

SELECT  @cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT
                                '],[' + t.Name
                        FROM    TESTTABLE AS t
                        ORDER BY '],[' + t.Name
                        FOR XML PATH('')
                      ), 1, 2, '') + ']'

SET @query = N'SELECT '+ @cols +' FROM
(SELECT t1.Name , t1.Count FROM TESTTABLE AS t1) p
PIVOT (MAX([Count]) FOR Name IN ( '+ @cols +' ))
AS pvt;'

EXECUTE(@query)

Explanation

1.The first part of the query

SELECT  @cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT
                        '],[' + t.Name
                FROM TESTTABLE AS t
                ORDER BY '],[' + t.Name
                FOR XML PATH('')
              ), 1, 2, '') + ']'

gives you a nice flattened result of your Name column values in a single row as follow

[Cheryl],[Drew],[Karen],[Kath],[Kirk],[Matt]  

You can learn more about the STUFF and XML PATH here and here.

2.SELECT + @cols + FROM will select all the rows as coloumn names for the final result set (pvt - step 3)

i.e

Select [Chery],[Drew],[Morgan],[Kath],[Kirk],[Matt] 

3.This query pulls all the rows of data that we need to create the cross-tab results. The (p) after the query is creating a temporary table of the results that can then be used to satisfy the query for step 1.

(SELECT t1.Name, t1.Count FROM  TESTTABLE AS t1) p

4.The PIVOT expression

PIVOT (MAX (Count) FOR Name IN ( @cols) AS pvt

does the actual summarization and puts the results into a temporary table called pvt as

Chery | Drew | Morgon | Kath | Kirk | Matt  
-------------------------------------------  
257     1500     13      500    200    76


See Using PIVOT and UNPIVOT.

You can use the PIVOT and UNPIVOT relational operators to change a table-valued expression into another table. PIVOT rotates a table-valued expression by turning the unique values from one column in the expression into multiple columns in the output, and performs aggregations where they are required on any remaining column values that are wanted in the final output. UNPIVOT performs the opposite operation to PIVOT by rotating columns of a table-valued expression into column values.

The quick answer is

SELECT Chery, Drew, Morgon, Kath, Kirk, Matt
FROM 
(SELECT [Name], [Count] From Foo)
PIVOT
(
   MIN([Count])
   FOR [Name] IN (Chery, Drew, Morgon, Kath, Kirk, Matt)
) AS PivotTable


If you want to avoid anything complicated like a pivot or the accepted answer, you can do this! (most of the code is just setting up the test data just in case anyone wants to try it)

/* set up your test table */
declare @TestData table (Name Varchar(80),[Count] int)    
insert into @TestData (Name, [count])
Select 'Chery' as name, 257 as [count]  
union all select 'Drew', 1500
union all select 'Morgon',13  
union all select 'Kath', 500  
union all select 'Kirk', 200  
union all select 'Matt', 76 

/* the query */
Declare @Query Varchar(max)
Select @Query=Coalesce(@query+', ','SELECT ') +Convert(VarChar(5),[count]) +' as ['+name+']'
from @TestData
Execute (@Query)
/* result 

Chery       Drew        Morgon      Kath        Kirk        Matt
----------- ----------- ----------- ----------- ----------- -----------
257         1500        13          500         200         76

*/
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜