使用临时表和存储过程来获取一些数据

时间:2013-05-22 10:46:13

标签: sql-server stored-procedures

我有一个项目,目的是如图所示分析结果:enter image description here

但是,我的表在此处的图像中显示如下:

enter image description here

现在,我在这个问题中使用我的标题进行搜索,看看如何使用我在图像2中的表格来实现我在图像1中显示的结果,以生成如此处所述的sql过程,但我被困住了,我需要你的帮助。

CREATE proc [dbo].[getScoreClassificationbySchools]
@NameofSchool nvarchar(31), @levelName nvarchar(5)
as 
Begin
create table #A(LevelNames varchar(50), SchoolSubject varchar (50))
create table #B(LevelNames varchar(50), TotalNostudent int, SchoolSubjectt varchar (50))
create table #C(LevelNames varchar(50), ScoreClassDistinction varchar (10), SchoolSubject varchar (50))
create table #D(LevelNames varchar(50), ScoreClassCredit varchar (10), SchoolSubject varchar (50))
create table #E(LevelNames varchar(50), ScoreClassPass varchar (10), SchoolSubject varchar (50))
create table #F(LevelNames varchar(50), ScoreClassFail varchar (10), SchoolSubject varchar (50))

insert into #A(LevelNames, SchoolSubject)
select distinct LevelName,  Subject from tb_schlist where @levelName =LevelName AND @NameofSchool = SchoolName 

insert into #B(LevelNames, TotalNostudent,SchoolSubjectt)
select distinct LevelName, count (LevelName) as TotalNoOfStudent, Subject from tb_schlist where @levelName =LevelName AND @NameofSchool = SchoolName 

insert into #C(LevelNames, ScoreClassDistinction, SchoolSubject)
select distinct LevelName, Grades, Subject from tb_schlist where  @levelName =LevelName and @NameofSchool = SchoolName and Grades='A1'

insert into #D(LevelNames, ScoreClassCredit, SchoolSubject)
select distinct LevelName, Grades, Subject from tb_schlist where @levelName =LevelName and @NameofSchool = SchoolName and Grades='B2'

insert into #E(LevelNames, ScoreClassPass, SchoolSubject)
select distinct LevelName, Grades, Subject from tb_schlist where  @levelName =LevelName and @NameofSchool = SchoolName and Grades='B3'

insert into #F(LevelNames, ScoreClassFail, SchoolSubject)
select distinct LevelName, Grades, Subject from tb_schlist where  @levelName =LevelName and @NameofSchool = SchoolName and Grades='C4'

SELECT t1.lnames , t2.SchoolSubject, t3.ScoreClassDistinction, t4.ScoreClassCredit, t5.ScoreClassPass, t6.ScoreClassFail from #A t1 join #B t2 on t1.LevelNameS = t2.LevelNames join #C t3 join #D t4 on t3.LevelNames = t4.LevelNames join #E t5 join #F t6  on t5.LevelNames = t6.LevelNames

1 个答案:

答案 0 :(得分:0)

试试这个:

select SUBJECT, 
[A1]+[B2]+[B3]+[C4]+[C5]+[C6] + [D7]+ [E8] + [F9] 
As TotalNoOfStudentsThatSat,
[A1],[B2],[B3],[C4],[C5],[C6] ,
 [A1]+[B2]+[B3]+[C4]+[C5]+[C6] AS [A1-C6]
 , [D7],[E8],[D7]+ [E8] AS [D7-E8]
 , [F9] from marks 
 pivot (
   count(grade) 
   for grade in ([A1],[B2],[B3],[C4],[C5],[C6],[D7],[E8],[F9])
 )PVT

SQL Fiddle