如何使用子查询查询学生分数?

时间:2012-01-19 13:21:41

标签: sql sql-server

我是SQL Server的新手,我有一些问题要问。我有如下表:

NAME   GRADE    SUBJECT 
JOHN    A       MATH
JOHN    C       PHYSIC
JENNY   B       PHYSIC
JENNY   C       MATH
KENNY   A       MATH
KENNY   B       PHYSIC

.....

我想查询

NAME  MATH    PHYSIC
JOHN    A       C
JENNY   C       B
KENNY   A       B

任何人都请帮帮我! 谢谢

5 个答案:

答案 0 :(得分:5)

如果并非所有名字都有所有科目的成绩

SELECT
   b.name, m.grade AS MATH, p.grade AS PHYSIC
FROM
    (
    SELECT DISTINCT name FROM MyTable
    ) b
    LEFT JOIN
    MyTable m ON b.name = m.name AND m.subject = "MATH"
    LEFT JOIN
    MyTable p ON b.name = p.name AND p.subject = "PHYSIC"

答案 1 :(得分:4)

您可以使用PIVOT(自SQL Server 2005起):

SELECT *
FROM (SELECT Name, Subject, Grade FROM Grades) o
PIVOT(MAX(Grade) FOR Subject IN ([Math], [Physic])) p

在PIVOT()运算符中你必须定义一个聚合函数,如果每个人都可以为一个主题有一个等级,那么MAX()或MIN()是完美的。

答案 2 :(得分:2)

您可以尝试:

SELECT t.name, q1.grade AS Math, q2.grade AS Physic
  (SELECT grade FROM your_table t1
  WHERE t.name = t1.name 
    AND t1.subject = "MATH") q1,
  (SELECT grade FROM your_table t2
  WHERE t.name = t2.name 
    AND t2.subject = "PHYSIC") q2
FROM your_table t
GROUP BY name

答案 3 :(得分:0)

您可以获取一个主题的所有记录,并使用同一个表加入另一个主题的记录:

select
  m.NAME,
  m.GRADE as MATH,
  p.GRADE as PHYSIC
from
  thetable m
  inner join thetable p on p.NAME = m.NAME and p.SUBJECT = 'PHYSIC'
where
  m.SUBJECT = 'MATH'

答案 4 :(得分:0)

使用PIVOT的例子:

DECLARE @Students TABLE 
(
    name varchar(10), 
    grade char(1), 
    [subject] varchar(10)
);

INSERT INTO @Students VALUES ('JOHN', 'A', 'MATH');
INSERT INTO @Students VALUES ('JOHN', 'C', 'PHYSIC');
INSERT INTO @Students VALUES ('JENNY', 'B', 'PHYSIC');
INSERT INTO @Students VALUES ('JENNY', 'C', 'MATH');
INSERT INTO @Students VALUES ('KENNY', 'A', 'MATH');
INSERT INTO @Students VALUES ('KENNY', 'B', 'PHYSIC');

SELECT *
FROM @Students AS Students
PIVOT 
( 
    MAX(Grade)
    FOR [subject] IN ([MATH], [PHYSIC])
) AS StudentGrades