2012-12-23 47 views
1

我有一個學生的表格,有一些關於他們是否需要一個教程等數據。下面是一個摘錄。顯示百分比的計數和計數兩個布爾值

| 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和存在= 1,當studentid = 111和存在= 0 但我不能工作了這兩樣東西。

i。我可以只進行一次計數查詢而不是分別計數嗎? 目前正與我的兩個單獨的查詢,我得到如

studentid = 111和存在= 1

| name | present | 
| John |  12 | 

studentid = 111和存在= 0

| name | absent | 
| John |  4 | 

但我會非常喜歡

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

ii.I想看看那些已經低於75%的課程。我已經做了一些關於avg函數的閱讀,但是我不確定如何爲此實現某些功能?

回答

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) 
+0

我不知道這是否有效,因爲我在@xdazz SQL小提琴和您的查詢中使用了我的示例數據,並基於相同的數據約翰出席時間不到75%,因爲他在那裏2/3(66%),但是當我運行它時,只有凱特出現? – ak85

+1

適用於我:http://sqlfiddle.com/#!2/7b2b1/4 – Barmar

1

你可以做象下面這樣:

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

這個偉大的工程對於問題的第一部分,謝謝! – ak85