You can use PIVOT to get the result, the only thing that you will need to do is add a row_number()
that is generated by partitioning the data by year
ordered by the number
. This unique sequence then allows you to return multiple rows for each year when you apply the aggregate function. Also since you want to convert string data you need to use either the max
or min
aggregate function:
select [1880], [1881], [1882]
from
(
select name, year,
row_number() over(partition by year
order by number desc) seq
from yourtable
) d
pivot
(
max(name)
for year in ([1880], [1881], [1882])
) p;
See SQL Fiddle with Demo. Returns:
| 1880 | 1881 | 1882 |
|---------|---------|---------|
| John | John | John |
| William | William | James |
| James | Charles | William |
| Charles | George | George |
| George | James | Charles |