如何在SELECT查询中使用count来创建多个表的视图?

时间:2016-05-27 09:33:21

标签: mysql sql

我有一个MySQL表格,提供不同学校学生的详细信息(如下所示)。 SchoolName定义了一所独特的学校。同样,StudentNameStudentId一起唯一地定义了学生。

| SchoolName | StudentName |  StudentId |

| ABC        | Tom         |  147852    |
| ABC        | Nix         |  258963    |
| ABC        | Bob         |  898596    |
| XYZ        | Ross        |  369369    |
| XYZ        | Jimmy       |  147852    |

我有另一张桌子,上面显示了学生的课程(如下所示)。在这里,一个角色' X'表示学生已完成该课程。空白意味着他没有采取这种做法。假设学生可以选择仅1门课程

| StudentName | StudentId | StudiesPhysics |  StudiesMaths |  StudiesChemistry  |

| Tom         | 147852    |                |  X            |                    |
| Nix         | 258963    |   X            |               |                    |
| Bob         | 898596    |                |  X            |                    |
| Ross        | 369369    |                |               |   X                |
| Jimmy       | 147852    |  X             |               |                    |

我想要一个视图,显示每所学校学习每门课程的学生人数(如下所示)。请帮我编写MySql查询以获得所需的结果。

| SchoolName | CountPhysics |  CountMaths |  CountChemistry  |

| ABC        | 1            |  2          | 0                |
| XYZ        | 1            |  0          | 1                |

2 个答案:

答案 0 :(得分:4)

SELECT
SN.SchoolName,
SUM(CASE WHEN C.StudiesPhysics='X' THEN 1 ELSE 0 END ) AS CountPhysics,
SUM(CASE WHEN C.StudiesMaths='X' THEN 1 ELSE 0 END ) AS CountMaths,
SUM(CASE WHEN C.StudiesChemistry='X' THEN 1 ELSE 0 END ) AS CountChemistry
FROM SchoolName AS SN
LEFT JOIN Course AS C
ON SN.StudentId=C.StudentID
GROUP BY SN.SchoolName

答案 1 :(得分:0)

使用简单的Count和Group By

DECLARE @Table1 TABLE 
    ( SchoolName  varchar(3),  StudentName  varchar(5),  StudentId  int)
;

INSERT INTO @Table1
    ( SchoolName ,  StudentName ,  StudentId )
VALUES
    ('ABC', 'Tom', 147852),
    ('ABC', 'Nix', 258963),
    ('ABC', 'Bob', 898596),
    ('XYZ', 'Ross', 369369),
    ('XYZ', 'Jimmy', 147852)
;




 DECLARE @Table2 TABLE 
    ( Name  VARCHAR(10) ,  Id  INT ,  Physics  VARCHAR(10),  Maths  VARCHAR(10),  Chemistry  VARCHAR(10))
;

INSERT INTO @Table2
    ( Name ,  Id ,  Physics ,  Maths ,  Chemistry )
VALUES
    ('Tom',147852,NULL,'X',NULL),
    ('Nix',258963,'X',NULL,NULL),
    ('Bob',898596,NULL,'X',NULL),
    ('Ross',369369,NULL,NULL,'X'),
    ('Jimmy',147852,'X',NULL,NULL)


    select T.SchoolName,
    COUNT(TT.Physics)Physics,
    COUNT(TT.Maths)Maths,
    COUNT(TT.Chemistry)Chemistry from @Table1 T
    INNER JOIN @Table2 TT
    ON T.StudentId = TT.Id AND TT.Name = T.StudentName
    GROUP BY T.SchoolName