2011-10-03 160 views
1

我的代碼是聚合函數平均值()和類型的無效使用:字符串

DataTable dtNew = new DataTable(); 
object o2 = dtAll.Compute("MIN(Price)", string.Empty); 
object o1 = dtAll.Compute("AVG(Price)",string.Empty);  

民返回最低..多數民衆贊成在正常工作。但平均生成錯誤

「集合函數Mean()和Type:String的使用無效」。

數據類型的價格在sql server中的列是十進制的。

+0

這不是一個完整的代碼示例,dtAll是什麼? –

+0

dtAll是可數據表。我想從結果集中找到min和avg。 –

+1

請給我解決方案,如果你知道.. –

回答

2

看來您的問題是Price列中的數據。我的直覺是該專欄將Price存儲爲文本;因此,當你打電話Min(Price)工作完全正常,因爲MIN定義爲strings,但當你cal AVG不喜歡它,因爲它不知道如何計算一串字符串的平均值。

總之,請確保Price列的數據類型是一個數字,並且您的代碼應該正常工作,因爲它沒有問題。

編輯

演示我的觀點:

DataTable t = new DataTable(); 
t.Columns.Add("Price"); 
t.Columns["Price"].DataType=typeof(string); 

for (int i = 0; i < 10; i++) 
{ 
    DataRow r = t.NewRow(); 
    r.ItemArray=new object[]{i}; 
    t.Rows.Add(r); 
} 

object min = t.Compute("MIN(Price)",string.Empty); 
Console.WriteLine("Min: " +min); //PRINTS Min: 0 
try 
{ 
    object avg = t.Compute("AVG(Price)", string.Empty); 
    Console.WriteLine("AVG: "+avg); 
} 
catch (Exception ex) 
{ 
    Console.WriteLine(ex.Message); 
} 

打印:

敏:字符串:0

聚合函數平均值()和類型的無效使用。

強制的數據類型爲int像這樣:

t.Columns["Price"].DataType=typeof(int); 

現在打印:

敏:0

AVG:4

+0

它不是這樣的... –

+0

當我直接從後端運行查詢其顯示結果.. –

+0

我得到了最小結果以及平均值 –