QQ网名大全

sql查询一个老师所带学员,横排显示,第一列显示老师名字,后面有几个学生显示几列

老师和学生的人数不确定,做应该可以做出来的,不过很烦。我把主要思路写下来,具体语句你自己写吧。将所有老师**临时表,PKID为主键
select distinct row_number()over(order by getdate())PKID,cph into#temp from[zcgl].[dbo].[jlsdxy]group by cph
declare@Count int-统计列数
declare@Sum int,@index int-老师总数量
select@Count=0,@Sum=count(*),@index=1 from#temp
while(@index)-循环**学生到临时表
begin
declare@cph varchar(50)-老师姓名
select@cph=cph from#temp where PKID=index-取出循环对应的老师名字
select distinct xm into#Temps from[zcgl].[dbo].[jlsdxy]where cph=cph-取出当前老师对应的学生
declare@StudentCount int-学生总数量
declare@StudentIndex int-循环初始值
select@StudentCount=count(xm),@StudentIndex=1 from#Temps
if(@StudentCount>@Count)-如果列数大于@Count,往临时表**列
begin
while(@Count)
begin
为临时表#temp**一列
set@Count=Count+1
end
end
declare@InsertSQL varchar(4000)-组合**语句SQL
while(@StudentIndex)
begin
在这里组合**语句列
end
while(@StudentIndex)
begin
在这里组合**语句值
end
执行**语句
查询临时表数据得到你想要的结果
end
怎么组合语句,怎么取列名自己想想吧。或许这个方法能对你有用
佚名
2024-05-30 04:53:34
最佳回答
类似问题(10)