我有一张桌子 出勤(SessionId,StudentId,IfPresent)
S1, Stu001, 1
S1, Stu002, 1
S1, Stu003, 1
S1, Stu004, 1
S1, Stu005, 1
S2, Stu001, 1
S2, Stu002, 0
S2, Stu065, 1
S3, Stu003, 0
.
.
.
主要收集有关分配到特定课程并参加课程的学生的信息。
我想要的是这样的报告
Attendance_report(SessionId,学生总数,出勤率)
S13, 20, 18
S15, 20, 17
S56, 40, 28
出勤将在where子句中使用IfPresent = 1进行计数 学生总数将来自一个没有任何where子句的计数
答案 0 :(得分:2)
试试这个
Select SessionId, count(*) as [Total Students],
sum(case when IfPresent = 1 then 1 else 0 end) as Attendance
from Attendance_report
group by SessionId
答案 1 :(得分:1)
按SessionId
分组,以便每个会话获得一个结果行并构建聚合(在您的情况下,这是一个简单的计数和总和):
select
sessionid,
count(*) as total_students,
sum(ifpresent) as attendance
from attendance
group by sessionid;
答案 2 :(得分:0)
BEGIN TRAN
Create Table #Attandance (Session_ID NVARCHAR(10),StudentId NVARCHAR(20), IfPresent INT )
INSERT INTO #Attandance
SELECT 'S1', 'Stu001', 1 UNION ALL
SELECT 'S1', 'Stu002', 1 UNION ALL
SELECT 'S1', 'Stu003', 1 UNION ALL
SELECT 'S1', 'Stu004', 1 UNION ALL
SELECT 'S1', 'Stu005', 1 UNION ALL
SELECT 'S2', 'Stu001', 1 UNION ALL
SELECT 'S2', 'Stu002', 0 UNION ALL
SELECT 'S2', 'Stu065', 1 UNION ALL
SELECT 'S3', 'Stu003', 0
SELECT Session_ID,COUNT(*)[Total Students],
SUM(IfPresent)from #Attandance
GROUP BY Session_ID
ROLLBACK TRAN