1

I have a table in the following format

Country_Code | 1960 | 1961 | 1962 | ..... | 2011
------------------------------------------------
IND          | va11 | va12 | va13 | ..... | va1x
AUS          | va21 | va22 | va23 | ..... | va2x
ENG          | va31 | va32 | va33 | ..... | va3x

I want to convert it into the below format

Country_Code | Year | Value
---------------------------
IND          | 1960 | va11
IND          | 1961 | va12
IND          | 1962 | va13
.
.
IND          | 2011 | va1x
AUS          | 1960 | va21
AUS          | 1961 | va22
AUS          | 1962 | va23
.
.
AUS          | 2011 | va2x
ENG          | 1960 | va31
ENG          | 1961 | va32
ENG          | 1962 | va33
.
.
ENG          | 2011 | va3x

How can this be achieved by sql query or sql server assembly ?

Taryn
  • 242,637
  • 56
  • 362
  • 405
Arjun Ganesan
  • 73
  • 1
  • 1
  • 8

1 Answers1

8

You can be done with UNPIVOT. If you have a known number of columns then you can hard-code the values:

select Country_Code, year, value
from yourtable
unpivot
(
  value 
  for year in ([1960], [1961], [1962], [2011])
) u

See SQL Fiddle with Demo

If you have an unknown number of columns, then you can use dynamic sql:

DECLARE @colsUnpivot AS NVARCHAR(MAX),
   @query  AS NVARCHAR(MAX)

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

set @query 
  = 'select country_code, year, value
     from yourtable
     unpivot
     (
        value
        for year in ('+ @colsunpivot +')
     ) u'

exec(@query)

See SQL Fiddle with Demo

Of you can even use a UNION ALL:

select country_code, '1960' year, 1960 value
from yourtable
union all
select country_code, '1961' year, 1961 value
from yourtable
union all
select country_code, '1962' year, 1962 value
from yourtable
union all
select country_code, '2011' year, 2011 value
from yourtable

See SQL Fiddle with Demo

Taryn
  • 242,637
  • 56
  • 362
  • 405
  • Wow!!! That was fast, really fast :) I have known number of columns hence first method of using UNPIVOT worked like a charm. Thanks a lot :) – Arjun Ganesan Oct 26 '12 at 19:26
  • @ArjunGanesan happy to help, be sure to accept the answer via the checkmark on the left it will help future visitors and it increases your reputation on the site. – Taryn Oct 26 '12 at 19:28