Since the data in your table is denormalized, I would suggest unpivoting the data first, then applying the PIVOT function to convert the values back into the final result that you want.
The first step is to unpivot the img1
and img2
columns, into multiple rows:
select d.name,
c.value,
c.col
+ cast(row_number() over(partition by d.name
order by d.name) as varchar(10)) new_col
from yourtable d
cross apply
(
select 'img', img1 union all
select 'img', img2
) c (col, value);
See Demo. The unpivot process will give you a result:
| NAME | VALUE | NEW_COL |
-----------------------------------
| Stack | lemon.jpg | img1 |
| Stack | (null) | img2 |
| Stack | (null) | img3 |
| Stack | orange.jpg | img4 |
| Stack | plum.jpg | img5 |
| Stack | (null) | img6 |
| Stack | grape.jpg | img7 |
| Stack | aubergine.jpg | img8 |
Then you can apply the pivot function to the values in new_col
, which was calculated by using row_number()
partitioned by the name:
select name, img1, img2, img3, img4, img5,
img6, img7, img8, img9, img10
from
(
select d.name,
c.value,
c.col
+ cast(row_number() over(partition by d.name
order by d.name) as varchar(10)) new_col
from yourtable d
cross apply
(
select 'img', img1 union all
select 'img', img2
) c (col, value)
) src
pivot
(
max(value)
for new_col in (img1, img2, img3, img4, img5,
img6, img7, img8, img9, img10)
) piv;
See SQL Fiddle with Demo