我想要显示这样的学生标记表:
---------------------------------------------------------
FIRST TURM | SECOND TURM|
---------------------------------------------------------
S_ID | SUB_NAME | OutOF | Marks | OutOF | Marks
---------------------------------------------------------
101 ENGLISH 100 90 100 90
101 HISTORY 100 80 100 80
101 MATHS 140 80 140 80
101 SANSKRIT 100 75 100 75
102 ENGLISH 100 80 100 80
102 HISTORY 100 80 100 80
102 MATHS 140 80 140 80
102 SANSKRIT 100 80 100 80
我使用pivot关键字来获取此输出
create table #t
(
S_ID int, SUB_NAME varchar(10), OutOF int, Marks int, Turm int
)
insert into #t (S_ID,SUB_NAME,turm,OutOF ,Marks)VALUES(101,'MATHS',1,140,80)
insert into #t (S_ID,SUB_NAME,turm,OutOF ,Marks)VALUES(101,'ENGLISH',1,100,90)
insert into #t (S_ID,SUB_NAME,turm,OutOF ,Marks)VALUES(101,'SANSKRIT',1,100,75)
insert into #t (S_ID,SUB_NAME,turm,OutOF ,Marks)VALUES(101,'HISTORY',1,100,80)
insert into #t (S_ID,SUB_NAME,turm,OutOF ,Marks)VALUES(102,'MATHS',1,140,80)
insert into #t (S_ID,SUB_NAME,turm,OutOF ,Marks)VALUES(102,'ENGLISH',1,140,80)
insert into #t (S_ID,SUB_NAME,turm,OutOF ,Marks)VALUES(102,'SANSKRIT',1,140,80)
insert into #t (S_ID,SUB_NAME,turm,OutOF ,Marks)VALUES(102,'HISTORY',1,140,80)
insert into #t (S_ID,SUB_NAME,turm,OutOF ,Marks)VALUES(101,'MATHS',2,140,80)
insert into #t (S_ID,SUB_NAME,turm,OutOF ,Marks)VALUES(101,'ENGLISH',2,100,90)
insert into #t (S_ID,SUB_NAME,turm,OutOF ,Marks)VALUES(101,'SANSKRIT',2,100,75)
insert into #t (S_ID,SUB_NAME,turm,OutOF ,Marks)VALUES(101,'HISTORY',2,100,80)
insert into #t (S_ID,SUB_NAME,turm,OutOF ,Marks)VALUES(102,'MATHS',2,140,80)
insert into #t (S_ID,SUB_NAME,turm,OutOF ,Marks)VALUES(102,'ENGLISH',2,140,80)
insert into #t (S_ID,SUB_NAME,turm,OutOF ,Marks)VALUES(102,'SANSKRIT',2,140,80)
insert into #t (S_ID,SUB_NAME,turm,OutOF ,Marks)VALUES(102,'HISTORY',2,140,80)
select *
from
(SELECT
S_ID, SUB_NAME,
CASE WHEN turm = 1 THEN 'FIRST TURM' ELSE 'SECOND TURM' END AS turm,
OutOF, Marks
FROM #t) S
PIVOT
(
MAX(Marks) FOR [turm] IN ([FIRST TURM], [SECOND TURM])) S
drop table #t
输出:
S_ID | SUB_NAME | OutOF |FIRST TURM |SECOND TURM
--------------------------------------------------
101 ENGLISH 100 90 90
101 HISTORY 100 80 80
101 MATHS 140 80 80
101 SANSKRIT 100 75 75
102 ENGLISH 140 80 80
102 HISTORY 140 80 80
102 MATHS 140 80 80
102 SANSKRIT 140 80 80
答案 0 :(得分:0)
这也可以这样解决:
select S_ID,SUB_NAME,OutOF,
Max(case when turm =1 then marks else 0 end) as 'First Turm',
Max(case when turm =2 then marks else 0 end) as 'Second Turm'
from t group by S_ID,SUB_NAME,OutOF