2011-06-16 116 views
0

我遇到的問題似乎來自我的where子句和硬編碼。 我有兩個表,一個是ID,另一個是ID和ID。SQL WHERE子句問題

所以我的代碼看起來有點像這樣:

SELECT AVG(CAST(c.Score AS DEC(10,2))) AS avgTestC, 
     AVG(CAST(d.Score AS DEC(10,2))) AS avgTestD, 
     AVG(CAST(e.Score AS DEC(10,2))) AS avgTestE, 
     AVG(CAST(f.Score AS DEC(10,2))) AS avgTestF, 
     COUNT(DISTINCT c.ID) AS CountC, 
     COUNT(DISTINCT d.ID) AS CountD, 
     COUNT(DISTINCT e.ID) AS CountE, 
     COUNT(DISTINCT f.ID) AS CountF 
FROM tblWithIds a, 
    JOIN tblScores b ON a.ID = b.ID AND b.Year = @Year 
    LEFT JOIN tblScores c ON a.ID = c.ID AND c.Year = @Year 
    LEFT JOIN tblScores d ON a.ID = d.ID AND d.Year = @Year 
    LEFT JOIN tblScores e ON a.ID = e.ID AND e.Year = @Year 
    LEFT JOIN tblScores f ON a.ID = f.ID AND f.Year = @Year 
WHERE c.TestC = 'Test C' 
     d.TestD = 'Test D' 
     e.TestE = 'Test E' 
     f.TestF = 'Test F' 

現在的問題是,當我增加更多的where子句和幾乎相同的「測試」 where子句,它給了我NULL值COUNT的一切和0。上面的代碼正常工作,但我使用的測試名稱非常相似,表格做得很差,因此所有「測試」名稱都在一列中。我無法調試,因爲現在我被困在MSSQL 05中。請幫忙!

編輯:使用下面的聚合函數SUM從EricZ越來越之後,如果任何人有興趣我發現

AVG(CASE WHEN b.Test = 'Test D' THEN CAST(b.Score AS DEC(10,2)) ELSE NULL END) AS avgTestC 

是對AVG聚合函數的正確形式。

回答

0

您可以使用CASE做COUNT,並且只需要連接表一旦

SELECT 
     AVG(CAST((CASE WHEN b.TestC = 'Test C' THEN b.Score ELSE 0 END) AS DEC(10,2))) AS avgTestC, 
     AVG(CAST((CASE WHEN b.TestD = 'Test D' THEN b.Score ELSE 0 END) AS DEC(10,2))) AS avgTestD, 
     AVG(CAST((CASE WHEN b.TestE = 'Test E' THEN b.Score ELSE 0 END) AS DEC(10,2))) AS avgTestE, 
     AVG(CAST((CASE WHEN b.TestF = 'Test F' THEN b.Score ELSE 0 END) AS DEC(10,2))) AS avgTestF,    
     SUM(CASE WHEN b.TestC = 'Test C' THEN 1 ELSE 0 END) AS CountC, 
     SUM(CASE WHEN b.TestD = 'Test D' THEN 1 ELSE 0 END) AS CountD, 
     SUM(CASE WHEN b.TestE = 'Test E' THEN 1 ELSE 0 END) AS CountE, 
     SUM(CASE WHEN b.TestF = 'Test F' THEN 1 ELSE 0 END) AS CountF 
FROM tblWithIds a, 
JOIN tblScores b ON a.ID = b.ID AND b.Year = @Year 
+0

這可以工作,但是你並沒有將AVG放在那裏。我不確定如何解決平均部分。 – jnewkirk 2011-06-16 15:55:41

+0

@ Newkirk21我使用AVG更新了查詢 – EricZ 2011-06-16 16:19:23

+0

謝謝大聲笑我實際上已經在指定的時間計算出來了:P但它的工作原理和感謝! – jnewkirk 2011-06-16 16:27:13

0

用例,而不是

SELECT SUM(CASE WHEN Something > 0 THEN Something ELSE 0 END) AS A, SUM(CASE WHEN Something2 > 0 THEN Something2 ELSE 0 END) AS B 
+0

我想不使用遞歸爲了完成任務,我需要在結果中包含所有平均「得分」,爲了做到這一點,我需要能夠從所有測試中獲得「得分」。 – jnewkirk 2011-06-16 15:23:42

+0

它不遞歸。它的集合邏輯。您可以使用AVG或其他任何聚合函數 – 2011-06-16 15:25:42

+0

對不起,我誤解了你想要傳達的內容謝謝,EricZ只是把它放在5年前的標準中,所以我可以理解。 – jnewkirk 2011-06-16 16:03:49