2015-08-14 195 views
0

我試圖計算關於該項目以及與某個項目關聯的說話人總數的所有說話人人數。第一個LEFT JOIN適用於所有揚聲器,但另一個僅適用於該項目的有源揚聲器,沒有任何幫助。該SQLFiddle在這裏從多個表格中查詢多個表格中的條件

http://sqlfiddle.com/#!3/b579d/1

但是當我嘗試在部分添加在那裏你會得到以前LEFT下有源音箱的

(LEFT JOIN (SELECT COUNT (tbl_SpeakerCard_Log.SpeakerName) 
WHERE tbl_Speaker_Log.Spoken = 0) 
ON tbl_AgendaList.AID = tbl_SpeakerCard_Log.AID) 

數量JOIN我得到一個錯誤。我100%確定查詢在某種形式上是錯誤的,但我不知道如何處理它。

*注意:說/活動是可以互換的,我只是用不同的措辭來澄清我在找什麼。

編輯:這是所需的輸出

http://imgur.com/yP1FKxg

+0

您可以包括什麼是慾望的輸出? –

+0

對不起,剛剛在表格中編輯了所需的輸出@JuanCarlosOropeza – khgove

+0

當您的採樣數據中只有一個揚聲器的Spoken bit = 1時,您如何獲得活動3和2? –

回答

1

可以使用條件聚集做到這一點:

SELECT  
    AgendaList.AID, 
    AgendaList.Item, 
    COUNT(SpeakerList.SPID) as SpeakerTotal, 
    SUM(CASE WHEN SpeakerList.Spoken = 0 THEN 1 ELSE 0 END) as ActiveSpeakers 
FROM  AgendaList 
LEFT JOIN SpeakerLIST ON AgendaList.AID = SpeakerList.AID 
GROUP BY AgendaList.AID, AgendaList.Item; 

Sample SQL Fiddle

或者你可以使用count而非總和(這可能會更清晰):

COUNT(CASE WHEN Spoken = 0 THEN Spoken END) as ActiveSpeakers 
+1

很多事情我不知道你可以在MSSQL ...或DB一般。非常感謝,我現在終於可以在我的項目中取得更多進展:D – khgove

1

SQL FIDDLE

WITH sTotal AS (
SELECT AgendaList.AID, AgendaList.Item, COUNT(SpeakerList.SPID) as SpeakerTotal 
FROM  AgendaList 
LEFT JOIN SpeakerLIST ON AgendaList.AID = SpeakerList.AID 
GROUP BY AgendaList.AID, AgendaList.Item 
), 
sActive AS (
SELECT AgendaList.AID, AgendaList.Item, COUNT(SpeakerList.SPID) as SpeakerActive 
FROM  AgendaList 
LEFT JOIN SpeakerLIST ON AgendaList.AID = SpeakerList.AID 
WHERE SpeakerLIST.Spoken = 0 
GROUP BY AgendaList.AID, AgendaList.Item 
) 
SELECT sTotal.*, sActive.SpeakerActive 
FROM sTotal left join 
    sActive on sTotal.AID = sActive.AID