SQL WHERE子句问题

时间:2011-06-16 15:13:37

标签: sql-server sql-server-2005

我遇到的问题似乎来自于我的where子句和硬编码。 我有两个表,一个是ID,另一个是ID和ID的分数。

所以我的代码看起来像这样:

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。请帮忙!

编辑:在使用EricZ下面的聚合函数SUM之后,如果有其他人感兴趣我发现了

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

是AVG聚合函数的正确形式。

2 个答案:

答案 0 :(得分:0)

改用CASE

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

答案 1 :(得分:0)

您可以使用CASE执行COUNT,只需要一次JOIN表

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