因爲在你的表中的數據規格化,我建議首先unpivoting的數據,然後應用PIVOT函數的值轉換回到你想要的最終結果。
的第一步是UNPIVOT的img1
和img2
列,爲多行:
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);
參見Demo。在逆透視過程中會給你一個結果:
| 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 |
然後你就可以將旋轉功能在new_col
的價值觀,這是通過使用row_number()
由名字分區計算:
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;
見SQL Fiddle with Demo
也許你應該重新設計你的數據庫模式。爲什麼你想要列中的數據,它似乎是稀疏的和無限的。 – Jodrell
@Jodrell L E G A C Y – NimChimpsky
什麼版本的sql server? – Taryn