【问题标题】:Get summarized/sorted data from SQL Server in ASP.NET从 ASP.NET 中的 SQL Server 获取汇总/排序的数据
【发布时间】:2018-08-01 17:34:58
【问题描述】:

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

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

所有学生的出勤情况总结:

  • I班学生人数:1人
  • II班学生人数:1人
  • III 班学生人数: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();
    }
}

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

【问题讨论】:

    标签: sql asp.net sql-server


    【解决方案1】:

    我认为您只需要条件聚合:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-22
      • 1970-01-01
      • 2019-12-30
      • 1970-01-01
      • 1970-01-01
      • 2013-08-14
      相关资源
      最近更新 更多