我想在SQL Server中将SQL结果格式化为给定格式

时间:2016-01-06 06:29:56

标签: sql-server

SQL结果:

id student_name class
----------------------
1  abc          1A  
2  xyz          1A 
3  dsk          1A
4  uij          1A
................. 
.................
.................
.................
.................
up 1000 results

我想以特定格式格式化数据

id1 student_name1 class1 id2 student_name2 class2 id3 student_name3 class3
-----------------------------------------------------------------------------------
1  abc             1A     2  abc            1A    3  abc          1A 
4  abc             1A     5  abc            1A    6  abc          1A
7  abc             1A   

1 个答案:

答案 0 :(得分:0)

正如评论所说,你的问题不是那么明确,所以我写的查询做了我认为你需要的...尝试一下,让我知道它是否符合你的要求

if object_ID('tempdb..#Temp') IS NOT NULL drop table #Temp
create table #Temp (ID int, Student_name nvarchar(100), class nvarchar(10))

insert into #Temp (ID, Student_Name, Class)
values
(1, 'abc', '1A'),
(2, 'xyz', '1A'),
(3, 'dsk', '1A'),
(4, 'uij', '1A'),
(5, 'sss', '1A'),
(6, 'fff', '1A'),
(7, 'ccc', '1A')

select t1.ID [ID1], 
   t1.student_name [student_name1],
   t1.class [class1],
   t2.ID [ID2], 
   t2.student_name [student_name2],
   t2.class [class2],
   t3.ID [ID3], 
   t3.student_name [student_name3],
   t3.class [class3]
from #Temp t1
LEFT join #Temp t2 on t1.ID + 1 = t2.ID
LEFT join #Temp t3 on t1.ID + 2 = t3.ID
where (t1.ID - 1) % 3 = 0