2016-03-02 40 views
0

我有一個表與事件信息(名稱,日期,描述等)和一個表包含出席信息(人,事件,無論他們是否參加)。我試圖從這兩個表中創建一個視圖,以顯示基於事件的「是」響應的總數和「否」響應的總數。這是我迄今爲止所擁有的。左連接與三張表不行爲如預期

SELECT e.id AS event, COUNT(yea.attendance) AS yes, COUNT(nea.attendance) AS no 
FROM event_information e 
LEFT JOIN event_attendance yea 
ON e.id = yea.event_id AND yea.attendance = 'Y' 
LEFT JOIN event_attendance nea 
ON e.id = nea.event_id AND nea.attendance = 'N' 
GROUP BY event; 

所以我希望這會返回每個事件ID(1,2,3和4)與'是'和'否'的相應數量的迴應。

event yes no 
    1  3  1 
    2  2  2 
    3  1  3 
    4  4  0 

而是返回

event yes no 
    1  3  3 
    2  4  4 
    3  3  3 
    4  4  0 

當我只參加event_attendance表一次檢索要麼是或否的結果如下,那麼正確的數字是通過提起。只有當我重新加入同一個表時,我纔會得到不正確的結果。

回答

2

使用條件,而不是聚集:

SELECT e.id AS event, SUM(a.attendance = 'Y') AS yes, SUM(a.attendance = 'N') AS no 
FROM event_information e LEFT JOIN 
    event_attendance a 
    ON e.id = a.event_id A 
GROUP BY event; 

你的方法行不通,因爲它會產生一個笛卡爾乘積爲「是」 ES和「無」 ES每個事件。如果兩個類別中都有零個或一個,那麼它應該可以工作。但是,如果兩者都不止一個,就會開始計算過多。

編輯:

而且,如果所有的事件至少有一個考勤記錄,那麼你不需要join

SELECT a.event_id AS event, 
     SUM(a.attendance = 'Y') AS yes, SUM(a.attendance = 'N') AS no 
FROM event_attendance a 
GROUP BY event_id; 
+0

現貨在,謝謝。它爲什麼在這裏生成笛卡爾產品? – ryansin

+0

@ user2696497這就是聯接所做的,它總是在所有正在聯接的表中創建一個笛卡爾積。 – Barmar

1

見,如果這個工程:

SELECT e.id AS event 
, SUM(CASE WHEN yea.attendance = 'Y' THEN 1 ELSE 0) AS yes 
, SUM(CASE WHEN yea.attendance = 'N' THEN 1 ELSE 0) AS no 
FROM event_information e 
LEFT JOIN event_attendance a ON e.id = a.event_id 
GROUP BY event;