日期:2014-05-18 浏览次数:20529 次
code name code1 name1 code2 name2 ------------------------------------------------------ 8 饶平五 23 伟雄 32 亚辉 9 江成 24 后面1号 33 亚中 10 陈明 26 老高 34 迎满 17 清水 27 818 38 炎松 20 灶强
--sql 2000 create table tb(code int,name nvarchar(10)) insert into tb values(8 ,N'饶平五') insert into tb values(9 ,N'江成') insert into tb values(10 ,N'陈明') insert into tb values(17 ,N'清水') insert into tb values(20 ,N'灶强') insert into tb values(23 ,N'伟雄') insert into tb values(24 ,N'后面1号') insert into tb values(26 ,N'老高') insert into tb values(27 ,N'818') insert into tb values(32 ,N'亚辉') insert into tb values(33 ,N'亚中') insert into tb values(34 ,N'迎满') insert into tb values(38 ,N'炎松') go select max(case when (px - 1)/n.cnt = 0 then code else null end) code, max(case when (px - 1)/n.cnt = 0 then name else null end) name, max(case when (px - 1)/n.cnt = 1 then code else null end) code1, max(case when (px - 1)/n.cnt = 1 then name else null end) name1, max(case when (px - 1)/n.cnt = 2 then code else null end) code2, max(case when (px - 1)/n.cnt = 2 then name else null end) name2 from ( select t.* , px = (select count(1) from tb where code < t.code) + 1 from tb t ) m , (select case when count(1)%3 = 0 then count(1)/3 else count(1)/3 + 1 end cnt from tb ) n group by (px - 1)%n.cnt drop table tb /* code name code1 name1 code2 name2 ----------- ---------- ----------- ---------- ----------- ---------- 8 饶平五 23 伟雄 33 亚中 9 江成 24 后面1号 34 迎满 10 陈明 26 老高 38 炎松 17 清水 27 818 NULL NULL 20 灶强 32 亚辉 NULL NULL (所影响的行数为 5 行) */ --sql 2005 create table tb(code int,name nvarchar(10)) insert into tb values(8 ,N'饶平五') insert into tb values(9 ,N'江成') insert into tb values(10 ,N'陈明') insert into tb values(17 ,N'清水') insert into tb values(20 ,N'灶强') insert into tb values(23 ,N'伟雄') insert into tb values(24 ,N'后面1号') insert into tb values(26 ,N'老高') insert into tb values(27 ,N'818') insert into tb values(32 ,N'亚辉') insert into tb values(33 ,N'亚中') insert into tb values(34 ,N'迎满') insert into tb values(38 ,N'炎松') go select max(case when (px - 1)/n.cnt = 0 then code else null end) code, max(case when (px - 1)/n.cnt = 0 then name else null end) name, max(case when (px - 1)/n.cnt = 1 then code else null end) code1, max(case when (px - 1)/n.cnt = 1 then name else null end) name1, max(case when (px - 1)/n.cnt = 2 then code else null end) code2, max(case when (px - 1)/n.cnt = 2 then name else null end) name2 from ( select t.* , px = row_number() over(order by code) from tb t ) m , (select case when count(1)%3 = 0 then count(1)/3 else count(1)/3 + 1 end cnt from tb ) n group by (px - 1)%n.cnt drop table tb /* code name code1 name1 code2 name2 ----------- ---------- ----------- ---------- ----------- ---------- 8 饶平五 23 伟雄 33 亚中 9 江成 24 后面1号 34 迎满 10 陈明 26 老高 38