SQL:如何显示通过和失败学生的百分比?

时间:2017-10-12 13:22:41

标签: sql sql-server sql-server-2008

我有一张表格,其中包含学生及其成绩的数据。

ID  Name  Result
1   St1   FAIL
2   St2   PASS
3   St3   PASS
4   St4   PASS
5   St5   FAIL
6   St6   PASS

我希望通过和失败的学生的总百分比四舍五入到小数点后两位。我怎么能做到这一点?

3 个答案:

答案 0 :(得分:6)

SQL:

SELECT 
    ROUND(
        SUM(
            CONVERT(
                FLOAT,
                CASE WHEN Result = 'PASS' THEN 1 
                     ELSE 0 
                     END
            )
        )
        /COUNT(*) * 100,
        2
    ) AS 'Percent Pass',
    ROUND(
        SUM(
            CONVERT(
                FLOAT,
                CASE WHEN Result = 'FAIL' THEN 1 
                     ELSE 0 
                     END
            )
        )
        /COUNT(*) * 100,
        2
    ) AS 'Percent Fail' 
FROM StudentsResults

结果:

Pass    Fail
66.67   33.33

答案 1 :(得分:2)

没有count()

的另一个选项

示例

Select Pass = round(avg(case when Result='Pass' then 100.0 else 0.0 end),2)
      ,Fail = round(avg(case when Result='Fail' then 100.0 else 0.0 end),2)
 From  YourTable

<强>返回

Pass    Fail
66.67   33.33

答案 2 :(得分:1)

使用group by子句怎么样?

select round(cast(count(Name) as decimal)/cast((select count(*) from StudentPassFail) as decimal)*100,2), result from StudentPassFail 
group by result;