sql - 从 ASP.NET 中的 SQL Server 获取汇总/排序的数据
问题描述
下面是我保存学生出勤率的 sql 表
我正在尝试创建一个汇总的出勤报告,如下所示:
所有学生的出勤总结:
- I班学生人数:1
- II班学生人数:1
- 三班学生人数:0
但我并没有找到正确的方法来做到这一点。下面是我试图用来实现这一目标的示例代码:
public void GetPresentCount()
{
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("select count(*) as 'TotalPresent' from stud_att where att='Present' and a_date='"+ systemdate +"'", con))
{
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
totstuds.InnerText = dr["TotalCount"].ToString();
}
else
{
totstuds.InnerText = "0";
}
}
}
con.Close();
}
}
public void GetAbsentCount()
{
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("select count(*) as 'TotalPresent' from stud_att where att='Present' and a_date='" + systemdate + "'", con))
{
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
totstuds.InnerText = dr["TotalCount"].ToString();
}
else
{
totstuds.InnerText = "0";
}
}
}
con.Close();
}
}
但我知道这不是正确的方法。
解决方案
我想你只想要条件聚合:
select class,
sum(case when att = 'Present' then 1 else 0 end) as attendance
from stud_att
where a_date = ?
group by class
order by class;
?
是传入日期的参数占位符。不要使用常量值处理 SQL 查询;将它们作为参数传入。
推荐阅读
- eclipse - Eclipse Photon 无法识别我的 Junit 5“运行方式”测试
- javascript - 在 Node.js 中将文件作为分离进程执行
- julia - 如何在 Julia 1.0 中安装软件包
- batch-file - 使用批处理文件卸载 wmic
- javascript - 带有ajax的PHP帖子不起作用
- bash - 如何使用单个变量获得多个输入?
- javascript - 为什么我可以通过数组向下循环,但不能向上循环 - Javascript
- php - 如何检查 Google Drive 文件是否与任何拥有 Google Drive API 文件链接的人共享?
- python - Matplotlib.FuncAnimation 工作,但使用 `interval = ... < 200` 时出现奇怪的异常
- mongodb - Mongo聚合 - 在一次调用中对字典中的多个项目求和