我正在努力使用正确的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
)
当然,Late
和Absent
列都返回相同的值,因为'where'的位置。
所以这样做(从右边开始)确定“10年级”成员学生的身份证。
然后,对于返回的每个学生ID,我需要它返回未经批准的缺席的类型记录,其中未批准的缺席类型为1,并且在下一列中,还返回类型为2的未批准缺勤计数。 / p>
如果我尝试像这样提交查询: -
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。
我可以做大多数基本的选择查询,但是当涉及到嵌套查询,联合,联接,内部时,我不在我的深度。非常感激任何的帮助。我绝对不确定我的(工作)查询是否以任何方式正确构造,'因为我是一个黑客。
答案 0 :(得分:21)
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