使用两个表计算bool列的百分比

时间:2016-09-10 22:01:11

标签: sql-server

有人可以帮我在SQL服务器中创建一个视图来获取新列中的百分比。例如,我有两个表格如下。

Table 1---> Subject          |      Table 2---->Exam
                             |
SubjectID     SubName        |      ExamID   SubjectID   Result (bool)
   1          Science        |        1        1            1
   2          Maths          |        2        1            1
   3          English        |        3        1            0
   4          History        |        4        2            0
   5          Art            |        5        2            1
   6          Geography      |        6        3            0
                             |        7        4            1
                             |

如您所见,许多科目没有考试,因此在联合视图中结果将为null。我想显示主题的通过百分比。例如,在结果列中,1 =传递,0 =失败。我希望结果看起来像下面显示空字段。

SubjectID    SubName    PassPercentage
    1        Science        66.66
    2        Maths          50
    3        English        0
    4        History        100
    5        Art            null
    6        Geography      null

4 个答案:

答案 0 :(得分:3)

下面:

SELECT 
Subject.SubjectId, 
Subject.SubName, 
(AVG(CONVERT(decimal,Exam.Result))*100) AS PassPercentage 
FROM Subject
LEFT JOIN Exam on Subject.SubjectId = Exam.SubjectId
GROUP BY Subject.SubjectId, Subject.SubName

您可以舍入百分比结果(2或无小数)并根据需要添加%符号。

答案 1 :(得分:1)

使用此查询:

Select *,
(Select Avg(Cast(Result as decimal)) From Exam Where SubjectID=S.SubjectID)*100 as PassPercentage
From Subject as S

结果是:

SubjectID   SubName         PassPercentage
----------- --------------- ---------------------------------------
1           Science         66.666600
2           Maths           50.000000
3           English         0.000000
4           History         100.000000
5           Art             NULL
6           Geography       NULL

(6 row(s) affected)

将对主题表的每一行执行子查询。

答案 2 :(得分:0)

做的:

select s.SubjectID, s.SubName, 
case COUNT(e.Result) 
    when 0 then null
    else SUM(CAST(e.Result AS INT)) * 100 / (COUNT(s.SubjectID))
end PassPrec

from Subject s
left join Exam e on s.SubjectID = e.SubjectID
group by s.SubjectID, s.SubName

有案例是获取null。 nulls不计入" count"功能

答案 3 :(得分:0)

你可以使用这样的代码

;with cte1 as (
select subjectid, sum(result) ResultCount
from exam group by subjectid
), cte2 as (
select e.subjectid, c.ResultCount, count(e.examid) TotalExams from cte1 c 
left join exam e on e.subjectid = c.subjectid
group by e.subjectid, c.ResultCount
) select s.subname, convert(decimal(10,2), (c.ResultCount/convert(decimal(10,2),c.TotalExams)) *100) as Percentage  from  subject s left join cte2 c
on s.subjectid = c.subjectid