2013-02-04 41 views
6

我用正确的SQL语法奋力一列返回一个特定值的计数不同的值相同的列多COUNT。SQL查询 - 与来自嵌套SELECT查询

此查询的工作(可能是不正确的语法,但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 
) 

当然,无论LateAbsent列返回,因为那里的“其中”是相同的值。

那么这是什么做的是(右)确定学生谁是“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三列。

我能做的最基本的选择查询,但是当涉及到嵌套查询,工会,加入,内部件我出我的深度。非常感激任何的帮助。绝不是我相信我的(工作)查询以任何方式结构正确,“怎么我在这一个黑客。

回答

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