SQL用于检索具有计算列的聚合数据

时间:2010-04-11 19:38:28

标签: sql sql-server-2005

对于大约30名学生,我有一张看起来像这样的表:

StudentID    Course*      CourseStatus
1            Math         Pass
1            English      Fail
1            Science      Pass
2            Math         Fail
2            English      Pass
2            Science      Fail
etc.

*在我的实际数据库中,“课程”列是一个CourseID,例如(1 =数学; 2 =英语等)引用'CourseName'表。我修改了上面的表格,只是为了说明问题的本质。

我想在SQL中编写一个查询(存储过程),它总结了给定课程的性能并返回以下内容:

EXEC usp_GetCourseSummary 'Math'

Total Students     Total Pass    % Pass    Total Fail    % Fail
25                 15            60        10            40

在这一段时间里,我一直在摸不着头脑。有什么想法吗?

1 个答案:

答案 0 :(得分:3)

试试这个:

CREATE PROCEDURE usp_GetCourseSummary
    @Course nvarchar(100)
AS     
    SET NOCOUNT ON;
    SELECT
        COUNT(StudentId) AS [Total Students],
        SUM(CASE WHEN CourseStatus = 'Pass' THEN 1 ELSE 0 END) AS [Total Pass],
        SUM(CASE WHEN CourseStatus = 'Pass' THEN 1 ELSE 0 END) * 100 / COUNT(*) AS [% Pass],
        SUM(CASE WHEN CourseStatus = 'Fail' THEN 1 ELSE 0 END) AS [Total Fail], 
        SUM(CASE WHEN CourseStatus = 'Fail' THEN 1 ELSE 0 END) * 100 / COUNT(*) AS [% Fail]
    FROM table1
    WHERE Course = @Course;
GO

EXEC usp_GetCourseSummary 'Math'

结果:

Total Students  Total Pass  % Pass  Total Fail  % Fail
2               1           50      1           50

测试数据:

CREATE TABLE Table1 (StudentID INT NOT NULL, Course NVARCHAR(100) NOT NULL, CourseStatus NVARCHAR(100) NOT NULL);
INSERT INTO Table1 (StudentID, Course, CourseStatus) VALUES
(1, 'Math', 'Pass'),
(1, 'English', 'Fail'),
(1, 'Science', 'Pass'),
(2, 'Math', 'Fail'),
(2, 'English', 'Pass'),
(2, 'Science', 'Fail');