根据列的总和计算不同的ID

时间:2013-11-25 12:45:51

标签: sql azure-sql-database

我觉得这应该是非常简单但不能理解它,我会感谢以下任何建议(我已经简化为关注我不能做的事情)。我正在使用Azure SQL。

我有一个结果表(称为testanswers),如下所示:

id | PupilId | NumMark
----------------------
1  | 10      | 1
2  | 20      | 2
3  | 10      | 2
4  | 20      | 0
5  | 10      | 1
6  | 20      | 2

我想计算在两个边界之间取得多个分数的学生人数(即不同的PupilId)。

我试过了:

SELECT COUNT(DISTINCT PupilId)
FROM testanswers
WHERE SUM(NumMark) >= 2 AND SUM(NumMark) <= 5

错误消息显示

  

聚合可能不会出现在WHERE子句中,除非它位于HAVING子句或选择列表中包含的子查询中,并且要聚合的列是外部引用

我很感激有关如何正确编码此查询的任何建议。

谢谢,

斯蒂芬

5 个答案:

答案 0 :(得分:3)

要为每个学生找到SUM(NumMArk),您必须GROUP BY PupilID

SELECT PupilId, SUM(NumMark)
FROM testanswers
GROUP BY PupilId ;

然后,只保留此总和介于25之间的行,您可以使用HAVING

SELECT PupilId, SUM(NumMark)
FROM testanswers
GROUP BY PupilId 
HAVING SUM(NumMark) >= 2 AND SUM(NumMark) <= 5 ;

如果你想计算有多少学生通过这个条件(而不是显示他们的ID),你必须将上面的内容包装在另一个查询中:

SELECT COUNT(*) AS result
FROM
  ( SELECT PupilId
    FROM testanswers
    GROUP BY PupilId 
    HAVING SUM(NumMark) BETWEEN 2 AND 5 
  ) AS tmp ;

这也适用于SQL-Server - 但不确定Azure版本:

SELECT DISTINCT COUNT(*) OVER () AS result
FROM testanswers
GROUP BY PupilId 
HAVING SUM(NumMark) BETWEEN 2 AND 5  ;

SQL-Fiddle

进行测试

答案 1 :(得分:1)

SELECT COUNT(PupilId) AS NUMBEROFPUPILS
FROM (SELECT PupilId FROM testanswers GROUP BY PupilId HAVING SUM(NumMark) BETWEEN 2 AND 5) AS TEMP;

答案 2 :(得分:0)

试试这个...

SELECT COUNT(DISTINCT PupilId)
FROM testanswers
Group by PupilId Having SUM(NumMark) >= 2 AND SUM(NumMark) <= 5

答案 3 :(得分:0)

查看数据http://sqlfiddle.com/#!2/ff287/1

尝试分组
SELECT  PupilId
FROM testanswers
group by PupilId
having SUM(NumMark) >= 2 AND SUM(NumMark) <= 5 

但是看起来你的桌子也缺少一个属性 - 或者你没有把它放在这里因为它不相关?

答案 4 :(得分:-2)

尝试GROUP BY

SELECT SUM(NumMark),COUNT(DISTINCT PupilId)
FROM testanswers
GROUP BY SUM(NumMark)
HAVING SUM(NumMark) >= 2 AND SUM(NumMark) <= 5