簡體   English   中英

使用DataTable時如何對列執行計算?

[英]How do I perform a calculation on a column when using a DataTable?

我需要計算一列的總和並將其顯示在total.Text 我怎樣才能做到這一點? 此列具有可隨時更改的無限數據。 我正在使用VS2010。 我是C#的新手。

例:

_____________________
| last_retail_price |
---------------------
|      500          |
|      200          |
|      5.60         |
---------------------
total.Text = 705.6  \\ The sum of column which I need

我的代碼:

private void add_click(object sender, EventArgs e) 
    SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\fuda\\Fuda.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
    SqlDataAdapter da = new SqlDataAdapter();
    DataTable tl = new DataTable();
    da.SelectCommand = new SqlCommand("Select last_ret_prc from pur_temp", con);
    con.Open();
    da.Fill(tl);

    object sum_obj;
    sum_obj = tl.Compute("sum(last_ret_prc)");
    total.Text = sum_obj.ToString();
    con.close();
}

像這樣的東西:

var con = new SqlConnection(/*your connection string*/);
var cmd = conn.CreateCommand();
cmd.CommandText = @"Select Sum(last_ret_prc) FROM pur_temp GROUP BY last_ret_prc";
string sum_obj = cmd.ExecuteScalar().ToString();

total.Text = sum_obj;

con.Dispose();

現在SQL查詢只返回一個值。 last_ret_prc的總和。 方法ExecuteScaler()返回第一行第一列的第一個值。

就目前而言,您的代碼永遠不會起作用:

  • 列名是last_retail_price,但您在代碼中使用了last_ret_prc。
  • con.close應該是con.Close()。
  • DataTable.Compute接受兩個參數“expression”和“filter”。 你仍然需要提供第二個參數,即使它是null。

我已經清理了代碼並在本地測試它並且工作正常:

SqlConnection con =
    new SqlConnection(
        @"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\fuda\Fuda.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
SqlDataAdapter da = new SqlDataAdapter();
DataTable tl = new DataTable();
da.SelectCommand = new SqlCommand("Select last_retail_price from pur_temp", con);
con.Open();
da.Fill(tl);

object sum_obj = tl.Compute("sum(last_retail_price)", null);
total.Text = sum_obj.ToString();
con.Close();

或者,如果您唯一的願望是顯示總數,那么您可能最好在一個SqlCommand中執行此操作:

con.Open();
var command = new SqlCommand("SELECT SUM(last_retail_price) FROM pur_temp", con);
var result = command.ExecuteScalar();
total.Text = result.ToString();
con.Close();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM