我想用一條SQL顯示這樣的結果

不知道這樣的要求能不能實現?
比如我有一張表T1,裏面只有一個字段1
裏面有100條記錄,如下所示:

字段1
A1
A2
A3
A4
...
A100

我想用一條SQL顯示這樣的結果
第一列    第二列    ...        第十列
A1        A11                  A91
A2        A12                  A92
A3        A13                  A93
...        ...                  ...
A10        A20                  A100

不知可否實現?當然,也不一定分成十列,可能是五列等等,請高手賜教。謝謝

 

 

--假設字段不存在相同值.
select
 
max(case (px - 1) % 10 when 0 then 字段1 else '' end) [c1],
 
max(case (px - 1) % 10 when 1 then 字段1 else '' end) [c2],
 
max(case (px - 1) % 10 when 2 then 字段1 else '' end) [c3],
 
max(case (px - 1) % 10 when 3 then 字段1 else '' end) [c4],
 
max(case (px - 1) % 10 when 4 then 字段1 else '' end) [c5],
 
max(case (px - 1) % 10 when 5 then 字段1 else '' end) [c6],
 
max(case (px - 1) % 10 when 6 then 字段1 else '' end) [c7],
 
max(case (px - 1) % 10 when 7 then 字段1 else '' end) [c8],
 
max(case (px - 1) % 10 when 8 then 字段1 else '' end) [c9],
 
max(case (px - 1) % 10 when 9 then 字段1 else '' end) [c10]
from
(
 
select * , px = (select count(1) from t1 where 字段1 < t.字段1) + 1 from t1 t
) m
group by (px - 1) / 10

--如果字段存在相同值.
--
sql 2000需要使用臨時表
select * , px = identity(int,1,1) into tmp from t1

select
 
max(case (px - 1) % 10 when 0 then 字段1 else '' end) [c1],
 
max(case (px - 1) % 10 when 1 then 字段1 else '' end) [c2],
 
max(case (px - 1) % 10 when 2 then 字段1 else '' end) [c3],
 
max(case (px - 1) % 10 when 3 then 字段1 else '' end) [c4],
 
max(case (px - 1) % 10 when 4 then 字段1 else '' end) [c5],
 
max(case (px - 1) % 10 when 5 then 字段1 else '' end) [c6],
 
max(case (px - 1) % 10 when 6 then 字段1 else '' end) [c7],
 
max(case (px - 1) % 10 when 7 then 字段1 else '' end) [c8],
 
max(case (px - 1) % 10 when 8 then 字段1 else '' end) [c9],
 
max(case (px - 1) % 10 when 9 then 字段1 else '' end) [c10]
from
(
 
select * , px = (select count(1) from tmp where 字段1 < t.字段1) + 1 from tmp t
) m
group by (px - 1) / 10

--不管字段是否存在相同值,sql 2005都可用row_number()解決
select
 
max(case (px - 1) % 10 when 0 then 字段1 else '' end) [c1],
 
max(case (px - 1) % 10 when 1 then 字段1 else '' end) [c2],
 
max(case (px - 1) % 10 when 2 then 字段1 else '' end) [c3],
 
max(case (px - 1) % 10 when 3 then 字段1 else '' end) [c4],
 
max(case (px - 1) % 10 when 4 then 字段1 else '' end) [c5],
 
max(case (px - 1) % 10 when 5 then 字段1 else '' end) [c6],
 
max(case (px - 1) % 10 when 6 then 字段1 else '' end) [c7],
 
max(case (px - 1) % 10 when 7 then 字段1 else '' end) [c8],
 
max(case (px - 1) % 10 when 8 then 字段1 else '' end) [c9],
 
max(case (px - 1) % 10 when 9 then 字段1 else '' end) [c10]
from
(
 
select * , px = row_number() over(order by 字段1) from t1
) m
group by (px - 1) / 10

 

 

 

http://topic.csdn.net/u/20091216/09/190c8c8b-de5d-4ea9-9866-3956cb0d1f8a.html?48518

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章