7

我正在努力使用正确的 SQL 语法来返回一列中特定值的计数。

此查询有效(可能语法不正确,但 SQL Server 2008 似乎很高兴)

SELECT StudentID, count(UnApproved)as Late, count(Unapproved) as Absent from results
WHERE unapproved=1 and StudentID in 
  (
    SELECT studentid  FROM [Results] 
    WHERE StudentYearLevel='10' and Date > 20130101) group by StudentID
  )

当然,由于 'where' 的位置,Late和列都返回相同的值。Absent

因此,这是(从右侧)确定属于“Year 10”成员的学生的 ID。

然后,对于返回的每个学生 ID,我需要它返回未批准缺勤类型为 1 的未批准缺勤计数,并在下一列中返回类型为 2 的未批准缺勤计数。

如果我尝试像这样提交查询:-

SELECT StudentID, count(UnApproved)as Late where unapproved=2, count(Unapproved) as Absent from results 
where unapproved=1 and StudentID in 
  (
    SELECT studentid  FROM [Results] where StudentYearLevel='10' and Date > 20130101
  )
group by StudentID

SQL Server 破解了它,并用红色给几乎整个查询加了下划线。

我需要结束这三列:-

StudentID | Late | Absent

并且三列具有具有适当计数的学生 ID。

我可以做最基本的选择查询,但是当涉及到嵌套查询、联合、连接、内部时,我已经超出了我的深度。非常感激任何的帮助。我决不能确定我的(工作)查询结构是否正确,因为我对此很擅长。

4

1 回答 1

24
SELECT StudentID, 
SUM(case when Unapproved =1 then 1 else 0 end) as Late, 
SUM(case when Unapproved =2 then 1 else 0 end) as Absent 
from results where 
StudentID in (SELECT studentid FROM [Results] where StudentYearLevel='10' and Date > 20130101) 
group by StudentID
于 2013-02-04T00:13:06.793 回答