Sql count查询来自同一列的不同值

时间:2014-07-12 06:23:44

标签: sql select count

我的表格看起来像new_attendance

Student_id | Attendance | Date       | Class     |Subject
-----------------------------------------------
2010639201 | No         |  1/10/2014 | Lecture   | CSC435
2010639202 | Yes        |  3/10/2014 | Tutorial  | CSC240
2010639203 | Yes        | 10/10/2014 | Tutorial  | CSP650
2010639201 | No         |  2/10/2014 | Lab       | CSC520
2010639201 | No         |  4/10/2014 | Tutorial  | ITT545
2010639204 | No         |  5/10/2014 | Tutorial  | CSP600
2010639205 | No         |  6/10/2014 | Tutorial  |ITT550
2010639206 | No         |  7/10/2014 | Lab       | CSC520

如何编写SQL计数查询来计算缺席次数(出勤次数="否")和课程数?

预期产出:

Student_id|No of absent|% of Absent|
------------------------------------
2010639202|3|3.57%

公式:

% of absent= ((no absent* (Lab+ Tutorial+ Lecture) ) / (14* subject_contachour) *100

2 个答案:

答案 0 :(得分:0)

看起来这就是你要找的东西:

SELECT `Class`, count(*)
FROM `new_attendance`
WHERE `Attendance` = 'No'
GROUP BY `Class`

答案 1 :(得分:0)

你可以这样做

CREATE TABLE new_attendance (student_id INT(11), attendance binary,
class VARCHAR(20), att_date DATE);

INSERT INTO `new_attendance` (`student_id`, `attendance`, `class`, `att_date`) VALUES
(2323,1,'CCNA','2013-09-12'), 
(453,0,'CCNA','2013-09-12'), 
(2435,1,'PHP','2013-09-12'), 
(324,0,'PHP','2013-09-12'), 
(2546,1,'CCNA','2013-09-12'), 
(897,0,'PHP','2013-09-12') 

SELECT `class`, count(*) AS total
FROM `new_attendance`
WHERE `attendance` = 0
GROUP BY `class`

结果是这样的

Class                 total
CCNA                    1
PHP                     2