2016-07-01 16 views
0

私はfunction analyze students results tableを作成しました。目標は、コンテンツタイプ別にグループ化された最高の平均結果を見つけることです。例:C#:Select文が正しい結果に表示されない

S_Id  ContentType  Result 
1    T    50 
1    V    70 
1    G    30 
1    G    40 
1    V    60 

Vの平均が最も高いので、必要な出力はVです。

これは私のコードですが、正しい結果を表示しません。 私の出力はテーブルの5番目の行を表示しています。

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

これは(あなたがパラメータ化されたSQLを使用することを学ぶべきであるが)* Cの#とは何か*を持っていることは明らかではありません。このクエリをMySQLで直接作成しようとしましたか? –

+0

私はC#でMySql文を書いた経験がありません – John

+0

しかし、問題はC#ではありません - SQLにあります。最初にMySQLツールでクエリを実行し、それをC#に移動してください。パラメータ化されたSQLを使用してください。 (あなたがそれを行う方法がわからない場合は、 "parameterized sql mysql c#"を検索すると多くの結果が得られます。 –

答えて

0

これはあなたが

+0

仕事を助けてくれてありがとう:) – John

0

、SQLクエリが正しくない欲しいものを得るでしょうあなたによって順序を追加した後、各ContentTypeを

select ContentType, AVG(result) as avgContent from dopractice where S_Id='" + studentId + "' GROUP BY ContentType order by AVG(result) desc limit 1; 

のためにあなたの平均的な結果を与えるウィル。それは以下のようなものです。

コード

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); 
+0

助けて助けてくれてありがとう、それは仕事です:) – John

関連する問題