C#如何获取当天的前10名

how to get the top 10 of the day C#

我在 SQL 服务器中有一个 table:

| date_Tim|机器|Case_wrong|

|:--------|:--------:|:----------:|

|07/03/21 16:53:PM|测试 1|1|

|07/03/21 16:58:PM|测试 1|1|

|07/03/21 16:59:PM|测试 1|1|

|07/03/21 16:58:PM|测试 2|1|

|07/03/21 16:59:PM|测试 2|1|

|07/03/21 17:00:PM|测试 2|1|

|07/03/21 17:01:PM|测试 3|1|

|08/03/21 16:58:PM|测试 3|1|

|08/03/21 16:58:PM|测试 2|1|

我想对日期为 07/03/22 的机器所有机器求和并填充到图表中 我试试代码

  private void loadchart()
        {
            var Today = DateTime.Now.ToString("dd/MM/yy");
            ChartTop.Series[0].Points.Clear();
            ChartTop.ChartAreas["ChartArea1"].AxisX.Interval = 1;
            string constring = ConfigurationManager.ConnectionStrings["Connstring"].ConnectionString;
            SqlConnection con = new SqlConnection(constring);
            SqlCommand sqlCmd = new SqlCommand();
            sqlCmd.Connection = con;
            sqlCmd.CommandType = CommandType.Text;
            SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
            try
            {
                sqlCmd.CommandText = sqlCmd.CommandText = "SELECT TOP 10 Machine, Sum(Case_wrong) as Case_wrong FROM tbl_Count_" + cbWorkcell.Text + " group by Machine order by SUM(Case_wrong)";
                DataSet dtRecord = new DataSet();
                sqlDataAdap.Fill(dtRecord);
                ChartTop.DataSource = dtRecord;
                //set the member of the chart data source used to data bind to the X-values of the series  
                ChartTop.Series["Series1"].XValueMember = "Machine";
                //set the member columns of the chart data source used to data bind to the X-values of the series  
                ChartTop.Series["Series1"].YValueMembers = "Case_wrong";
             //   ChartTop.Series[0].ChartType = SeriesChartType.Pie;
                con.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

它有效,但它需要我 table 中的所有数据进行计算。有没有办法按日期过滤数据并在那里求和? 请帮我!谢谢

出现的是 date_Tim 是一个日期时间字段,如果是这样,那么您需要在查询中添加一个 where 子句,我假设您提到的日期 (07/03 /22) 是 DD/MM/YY 基于需要更新查询以添加如下子句

"SELECT TOP 10 Machine, Sum(Case_wrong) as Case_wrong FROM tbl_Count_" + cbWorkcell.Text + " WHERE date_Tim >='2022-03-07 00:00:00.000'  group by Machine order by SUM(Case_wrong)"

请注意@madreflection 指出了严重错误,请更正它们有关 SQL 注入的更多详细信息 here

编辑 1: 如果您只是在寻找特定的一天

"SELECT TOP 10 Machine, Sum(Case_wrong) as Case_wrong FROM tbl_Count_" + cbWorkcell.Text + " WHERE CAST(date_Tim AS DATE)  ='2022-03-07'  group by Machine order by SUM(Case_wrong)"

如果您要查找当前日期

"SELECT TOP 10 Machine, Sum(Case_wrong) as Case_wrong FROM tbl_Count_" + cbWorkcell.Text + " WHERE CAST(date_Tim AS DATE)  = GETDATE()  group by Machine order by SUM(Case_wrong)"