显示计数百分比并计算两个布尔值

时间:2012-12-23 09:31:51

标签: php mysql

我有一张学生表,其中有一些关于他们是否参加教程的数据等。下面有一个摘录。

|   id |   studentid | name |  present | 
|   1  |   111       | John |       1  | 
|   2  |   222       | Kate |       0  | 
|   3  |   333       | Matt |       1  | 
|   4  |   111       | John |       0  | 
|   5  |   111       | John |       1  | 

我可以做一个计数来说明例如studentid = 111和present = 1以及studentid = 111和present = 0。 但我无法解决这两件事。

我。我可以只进行一次计数查询,而不是分别进行计数吗? 目前我正在进行两个单独的查询,例如

studentid = 111 and present = 1

| name |  present | 
| John |       12 | 

studentid = 111 and present = 0

| name |  absent | 
| John |       4 | 

但我最喜欢

| name |  present |  absent | 
| John |       12 |       4 | 

ii。我想看看那些不到75%的学生。我已经完成了关于avg函数的一些阅读,但是我不确定如何为此实现一些东西?

2 个答案:

答案 0 :(得分:2)

列出已达到不到75%课程的学生:

SELECT
  studentid,
  name, 
  SUM(present) AS present,
  SUM(present = 0) AS absent
FROM your_table
GROUP BY studentid, name
HAVING present < .75 * (present+absent)

答案 1 :(得分:1)

你可以这样做:

SELECT
  studentid,
  name, 
  SUM(present = 1) AS present,
  SUM(present = 0) AS absent
FROM your_table
GROUP BY studentid, name