我创建了功能分析学生结果表。目标是:找到按内容类型分组的最高平均结果。例如:
S_Id ContentType Result
1 T 50
1 V 70
1 G 30
1 G 40
1 V 60
我需要的输出是V,因为V的平均值是最高的。
这是我的代码,但它没有显示正确的结果: 我的输出显示表格中的第五行。
public string analyzeResultTable(string studentId)
{
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["AHSConnection"].ToString();
DataSet ds = new DataSet();
DataSet dsAns = new DataSet();
string BestPrefrence = "";
using (MySqlConnection conn = new MySqlConnection(connStr))
{
conn.Open();
MySqlCommand cmd2 =
new MySqlCommand(
"Select ContentType, MAX(avgContent) from (select ContentType, AVG(result) as avgContent from dopractice where S_Id='" +
studentId + "' GROUP BY ContentType) AS T", conn);
MySqlDataAdapter da = new MySqlDataAdapter(cmd2);
da.Fill(ds);
conn.Close();
}
if (ds.Tables[0].Rows.Count > 0)
{
BestPrefrence = ds.Tables[0].Rows[0]["ContentType"].ToString();
}
return BestPrefrence;
}
答案 0 :(得分:0)
这将为您提供每个ContentType的平均结果
select ContentType, AVG(result) as avgContent from dopractice where S_Id='" + studentId + "' GROUP BY ContentType order by AVG(result) desc limit 1;
添加订单后,您将得到您想要的内容
答案 1 :(得分:0)
您的SQL查询不正确。它可以是下面的东西。
<强>代码强>
MySqlCommand cmd2 = new MySqlCommand("select ContentType, AVG(Result) as AvgContent
from dopractice
where S_Id='" + studentId + "'
group by ContentType order by 2 desc limit 1;", conn);
我强烈建议您使用参数化查询来避免sql注入。
<强>代码强>
MySqlCommand cmd2 = new MySqlCommand("select ContentType, AVG(Result) as AvgContent
from dopractice
where S_Id= @S_Id
group by ContentType order by 2 desc limit 1;", conn);
cmd2.Parameters.AddWithValue("@S_Id", studentId);