Monday, November 25, 2013

How do I simply switch columns with rows in SQL? Is there any simple command to transpose?
ie turn this result:
        Paul  | John  | Tim  |  Eric
Red     1       5       1       3
Green   8       4       3       5
Blue    2       2       9       1
into this:
        Red  | Green | Blue
Paul    1       8       2
John    5       4       2
Tim     1       3       9
Eric    3       5       1
PIVOT seems too complex for this scenario.
share|improve this question
add comment

2 Answers

There are several ways that you can transform this data. In your original post, you stated that PIVOTseems too complex for this scenario, but it can be applied very easily using both the UNPIVOT andPIVOT functions in SQL Server.
However, if you do not have access to those functions this can be replicated using UNION ALL toUNPIVOT and then an aggregate function with a CASE statement to PIVOT:
Create Table:
CREATE TABLE yourTable([color] varchar(5), [Paul] int, [John] int, [Tim] int, [Eric] int);

    ([color], [Paul], [John], [Tim], [Eric])
    ('Red', 1, 5, 1, 3),
    ('Green', 8, 4, 3, 5),
    ('Blue', 2, 2, 9, 1);
Union All, Aggregate and CASE Version:
select name,
  sum(case when color = 'Red' then value else 0 end) Red,
  sum(case when color = 'Green' then value else 0 end) Green,
  sum(case when color = 'Blue' then value else 0 end) Blue
  select color, Paul value, 'Paul' name
  from yourTable
  union all
  select color, John value, 'John' name
  from yourTable
  union all
  select color, Tim value, 'Tim' name
  from yourTable
  union all
  select color, Eric value, 'Eric' name
  from yourTable
) src
group by name
The UNION ALL performs the UNPIVOT of the data by transforming the columns Paul, John, Tim, Eric into separate rows. Then you apply the aggregate function sum() with the case statement to get the new columns for each color.
Unpivot and Pivot Static Version:
Both the UNPIVOT and PIVOT functions in SQL server make this transformation much easier. If you know all of the values that you want to transform, you can hard-code them into a static version to get the result:
select name, [Red], [Green], [Blue]
  select color, name, value
  from yourtable
    value for name in (Paul, John, Tim, Eric)
  ) unpiv
) src
  for color in ([Red], [Green], [Blue])
) piv
The inner query with the UNPIVOT performs the same function as the UNION ALL. It takes the list of columns and turns it into rows, the PIVOT then performs the final transformation into columns.
Dynamic Pivot Version:
If you have an unknown number of columns (Paul, John, Tim, Eric in your example) and then an unknown number of colors to transform you can use dynamic sql to generate the list to UNPIVOT and then PIVOT:
    @query  AS NVARCHAR(MAX),
    @colsPivot as  NVARCHAR(MAX)

select @colsUnpivot = stuff((select ','+quotename(
         from sys.columns as C
         where C.object_id = object_id('yourtable') and
      <> 'color'
         for xml path('')), 1, 1, '')

select @colsPivot = STUFF((SELECT  ',' 
                      + quotename(color)
                    from yourtable t
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 

set @query 
  = 'select name, '+@colsPivot+'
        select color, name, value
        from yourtable
          value for name in ('+@colsUnpivot+')
        ) unpiv
      ) src
        for color in ('+@colsPivot+')
      ) piv'

The dynamic version queries both yourtable and then the sys.columns table to generate the list of items to UNPIVOT and PIVOT. This is then added to a query string to be executed. The plus of the dynamic version is if you have a changing list of colors and/or names this will generate the list at run-time.
All three queries will produce the same result:
| Eric |   3 |     5 |    1 |
| John |   5 |     4 |    2 |
| Paul |   1 |     8 |    2 |
|  Tim |   1 |     3 |    9 |
share|improve this answer
I should have emphasized that I want a method to transpose the results of a query on a database. A simple transpose type command that can be executed on the result set from a query without having to know anything about the query itself, or the columns, tables etc it is extracting info from. Something like: (TRANSPOSE (SELECT......)) In my example given above, imagine that the first table is a result set generated from a very complex query involving multiple tables, unions, pivots etc. Yet the result is a simple table. I just want to flip the columns with rows in this result. –  edezzie Nov 14 '12 at 18:46
I'm passing the result to a c# DataTable. I can build a simple method 'Transpose(Datatable dt)' to do it there, but is there anything in SQL to do this. –  edezzie Nov 14 '12 at 18:47
@edezzie there is not a simple way in SQL to do this. You could probably alter the dynamic version to pass in the table name and pull the info from the system tables. –  bluefeet Nov 14 '12 at 18:55
add comment


oakleyses said...

louis vuitton handbags, oakley sunglasses, louboutin, longchamp outlet, nike shoes, louis vuitton outlet stores, chanel handbags, burberry outlet, prada outlet, jordan shoes, tiffany and co, michael kors outlet, tory burch outlet, louis vuitton outlet, longchamp handbags, nike free, true religion jeans, michael kors outlet, kate spade outlet, polo ralph lauren outlet, tiffany and co, prada handbags, polo ralph lauren outlet, michael kors outlet, michael kors outlet, longchamp handbags, oakley sunglasses, ray ban sunglasses, kate spade handbags, burberry outlet, louis vuitton outlet, louboutin outlet, louboutin, coach factory outlet, air max, air max, coach outlet, gucci outlet, christian louboutin shoes, michael kors outlet, coach purses, ray ban sunglasses, michael kors outlet, louis vuitton, coach outlet store online, true religion jeans, oakley sunglasses cheap

oakleyses said...

ralph lauren, lululemon, air max, hollister, north face, nike air max, polo lacoste, vanessa bruno, timberland, vans pas cher, louboutin, louis vuitton, oakley pas cher, air max pas cher, nike roshe run, air max, true religion outlet, barbour, sac longchamp, air force, hollister, sac louis vuitton, nike free, polo ralph lauren, nike trainers, louis vuitton uk, nike roshe, sac hermes, longchamp, michael kors, sac burberry, sac guess, mulberry, new balance pas cher, converse pas cher, sac louis vuitton, hogan outlet, nike tn, north face, true religion outlet, ray ban pas cher, michael kors, air jordan, nike blazer, nike free pas cher, michael kors pas cher, abercrombie and fitch, ray ban sunglasses

oakleyses said...

mac cosmetics, mont blanc, marc jacobs, canada goose outlet, nike huarache, vans shoes, soccer jerseys, hollister, giuseppe zanotti, beats by dre, abercrombie and fitch, longchamp, insanity workout, celine handbags, bottega veneta, ghd, nfl jerseys, north face outlet, chi flat iron, ugg boots, birkin bag, ugg australia, canada goose, herve leger, ugg pas cher, rolex watches, valentino shoes, canada goose uk, canada goose, ferragamo shoes, canada goose, ugg boots, uggs outlet, north face jackets, soccer shoes, asics running shoes, new balance shoes, p90x, lululemon outlet, canada goose jackets, mcm handbags, instyler, babyliss pro, ugg, wedding dresses, jimmy choo outlet, reebok outlet, nike roshe run

oakleyses said...

parajumpers, karen millen, air max, converse, pandora charms, moncler, louboutin, moncler, links of london, lancel, juicy couture outlet, oakley, hollister, pandora charms, supra shoes, thomas sabo, canada goose, gucci, wedding dresses, timberland boots, swarovski crystal, air max, coach outlet store online, moncler, ray ban, canada goose, moncler, ugg, louis vuitton, swarovski, hollister, montre homme, moncler, hollister clothing store, ralph lauren, rolex watches, moncler outlet, moncler, iphone 6 cases, baseball bats, juicy couture outlet, toms shoes, vans, pandora jewelry, ugg, converse shoes

Zheng junxai5 said...

hermes outlet
burberry outlet online
louis vuitton outlet
true religion jeans
oakley vault
celine outlet
kids lebron shoes
jordan retro 8
ray ban sunglasses
air jordan femme
timberland outlet
longchamp outlet
polo ralph lauren
coach outlet online
cheap oakley sunglasses
true religion outlet
hollister clothing
ralph lauren clearance outlet
nike running shoes for men
coach factory outlet
ghd hair straighteners
ghd flat iron
north face jackets
lebron 13
kate spade handbags
louis vuitton outlet
louis vuitton bags
gucci belts
michael kors handbags
louis vuitton purses
jordan retro 13
louis vuitton outlet
coach outlet
coach factory outlet online
michael kors outlet online
true religion outlet
replica watches
true religion jeans

raybanoutlet001 said...

kobe sneakers
kobe byrant shoes
ralph lauren online,cheap ralph lauren
michael kors outlet online
fitflops sale
cheap air jordans
huarache shoes
nike huarache sale
cheap jordans
air jordan shoes
michael kors handbags
cheap jordans online
michael kors outlet
michael kors outlet
nike huarache
michael kors handbags,michael kors handbags clearance,michael kors clearance
nfl jerseys from china
true religion store
nmd adidas store
air jordan shoes
adidas yeezy boost
michael kors outlet online