Sql 为什么我的查询不起作用。我写了一个查询,以确定缺席人数和出席人数

Sql 为什么我的查询不起作用。我写了一个查询,以确定缺席人数和出席人数,sql,sql-server,tsql,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

这是我为我的软件写的一篇文章,但没有给出正确的结果。我想计算学生的出席人数和缺席人数。

使用条件聚合:

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'

您的子查询与外部查询不同,它应该相互关联:

但是,您可以在单个
select
语句中使用
case
表达式而不是两个子查询:

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

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

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;

“它没有给出正确的结果”什么是正确的结果?当前数据在哪些方面不同?您可以改进您的数据模型。学生应存储在自己的表中,而不是
考勤表中。然后通过外键链接
学生
出勤
表。否则,你必须在每次出勤时重复它的名字,而且你不能让一个学生没有出勤。即使这是解决办法,我也不喜欢在问题清楚之前张贴答案。否则人们就不会意识到解释这个问题的重要性。这个问题对任何未来的读者都没有帮助。@TimSchmelter,我完全同意你的意见,下次我会按照你的建议做,非常感谢你的回答:)但当我执行查询时,它显示这个错误消息102,级别15,状态1,第2行“=”附近的语法不正确。@user10379355。您在
案例中的
表达式中错过了
,现在它起作用了。他什么时候失踪的。谢谢大家帮助我:)
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