1. 程式人生 > >Sql縱轉橫

Sql縱轉橫

selectdistinct Sub_name as Sub_name,a.Sub_Code 
into #temptin
from t_ExamSubject a,t_SubjectManage b
where a.Exa_Code ='2'
and a.Sub_Code = b.Sub_Code
orderby a.Sub_Code;

select a.*,stu_Name,sub_Name 
into #tempMain
from t_resultManage a,t_StudentManage b,t_subjectManage c 
where a.Stu_Code = b.Stu_Code and a.Sub_code 
= c.Sub_code

declare@sqlvarchar(8000)
set@sql='select stu_Name as 學生姓名';
select@sql=@sql+',max(case sub_Name 
when 
'''+sub_Name+''' then sub_numeric end) ['+sub_Name+']' 
from #temptin;set@sql=@sql+' from #tempMain group by stu_code,stu_name order by stu_code';

exec(@sql)
droptable #temptin
droptable #tempmain

橫轉豎