为什么我的查询无法正常工作。我写了一个查询来识别缺席人数和现在人数

时间:2018-09-18 09:02:35

标签: sql sql-server tsql

select [First Name],[Last Name],Class,
(
    select count([Date]) from Attendence where [Roll Number] ='1' and [Student Status] ='P' 
) as [No Of Present],
(
    select count([Date]) from Attendence where [Roll Number] ='1' and [Student Status] ='A'
)as [No Of Absent]
from Attendence
where [Date] between '2018-09-1' and '2018-09-30'

这是我为我的软件写的,但没有给出正确的结果。我想计算学生现在和缺勤的数量。

3 个答案:

答案 0 :(得分:1)

使用条件聚合:

select [First Name],[Last Name],Class from
count(case [Student Status] ='P' then 1 end) as [No Of Present], 
count(case [Student Status] ='A'  then 1 end)as [No Of Absent] 
from Attendence where [Date] between '2018-09-1' and '2018-09-30' and [Roll Number] ='1'
group by [First Name],[Last Name],Class

答案 1 :(得分:0)

您的子查询与外部查询不同,应将其关联:

但是,您可以使用带有select表达式的单个case语句来代替两个子查询:

select [First Name], [Last Name], Class, 
       sum(case when [Student Status] = 'P' then 1 else 0 end) as [No Of Present], 
       sum(case when [Student Status] = 'A' then 1 else 0 end) as [No Of Absent] 
from Attendence at
where [Date] between '2018-09-1' and '2018-09-30' and [Roll Number] = '1'
group by [First Name], [Last Name], Class;

答案 2 :(得分:0)

我认为您的查询可能有效,但是您忘记了使用distinct。请找到以下更正的查询:

select distinct [First Name],[Last Name],Class,
(
select count([Date]) from Attendence where [Roll Number] ='1' and [Student Status] ='P' 
) as [No Of Present],
(
select count([Date]) from Attendence where [Roll Number] ='1' and [Student Status] ='A'
)as [No Of Absent]
from Attendence
where [Date] between '2018-09-1' and '2018-09-30'
group by [First Name],[Last Name],Class