首页 > 解决方案 > 从 ASP.NET 中的 SQL Server 获取汇总/排序的数据

问题描述

下面是我保存学生出勤率的 sql 表

检查此图像

我正在尝试创建一个汇总的出勤报告,如下所示:

所有学生的出勤总结:

但我并没有找到正确的方法来做到这一点。下面是我试图用来实现这一目标的示例代码:

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();
    }
}

但我知道这不是正确的方法。

标签: sqlasp.netsql-server

解决方案


我想你只想要条件聚合:

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 查询;将它们作为参数传入。


推荐阅读