在 DataView 过滤器中使用聚合函数

发布于 2024-09-03 02:30:53 字数 469 浏览 6 评论 0原文

我有一个数据表,其中有一列(“利润”)。我想要的是获得该表中所有值的总和。我尝试按以下方式执行此操作...

DataTable dsTemp = new DataTable();

dsTemp.Columns.Add("Profit");

DataRow dr = null;

dr = dsTemp.NewRow();
dr["Profit"] = 100;
dsTemp.Rows.Add(dr);

dr = dsTemp.NewRow();
dr["Profit"] = 200;
dsTemp.Rows.Add(dr);

DataView dvTotal = dsTemp.DefaultView;
dvTotal.RowFilter = " SUM ( Profit ) ";

DataTable dt = dvTotal.ToTable();

但是应用过滤器时出现错误... 我如何获得变量中利润列的总和

谢谢...

i have a DataTable that has a column ("Profit"). What i want is to get the Sum of all the values in this table. I tried to do this in the following manner...

DataTable dsTemp = new DataTable();

dsTemp.Columns.Add("Profit");

DataRow dr = null;

dr = dsTemp.NewRow();
dr["Profit"] = 100;
dsTemp.Rows.Add(dr);

dr = dsTemp.NewRow();
dr["Profit"] = 200;
dsTemp.Rows.Add(dr);

DataView dvTotal = dsTemp.DefaultView;
dvTotal.RowFilter = " SUM ( Profit ) ";

DataTable dt = dvTotal.ToTable();

But i get an error while applying the filter...
how can i get the Sum of the Profit column in a variable

thank you...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

櫻之舞 2024-09-10 02:30:53

将数据列设置为数字类型(int、decimal 等):

DataColumn col = new DataColumn("Profit", typeof(int));
dsTemp.Columns.Add(col);

使用 计算

int total = dsTemp.Compute("Sum(Profit)", "");

请注意,聚合不是一种过滤器,这是您所采用的方法的主要问题。

Set the datacolumn to a numeric type (int, decimal, whatever):

DataColumn col = new DataColumn("Profit", typeof(int));
dsTemp.Columns.Add(col);

Use Compute:

int total = dsTemp.Compute("Sum(Profit)", "");

Note that aggregation is not a type of filter, which is the main problem with the approach you are tyring.

几度春秋 2024-09-10 02:30:53

我按照建议使用了 DataTable 的 Compute 方法,效果很好。我应用了与 DataView 相同的过滤(用于在数据网格中显示排序和过滤的数据)以及聚合函数。

string SingleVocheridSale ="1";

 DataView view = new DataView(dt);
 view.RowFilter = string.Format("VOCHID='" + SingleVocheridSale + "'");
 dataGridview1.DataSource = view;
 object sumObject;
 sumObject = dt.Compute("Sum(NETAMT)", view.RowFilter);
 lable1.Text = sumObject.ToString();

I used the DataTable's Compute method as suggested, and it works fine. I apply the same filtering as I use for the DataView (which is used to display the sorted and filtered data in the data grid) together with an aggregate function.

string SingleVocheridSale ="1";

 DataView view = new DataView(dt);
 view.RowFilter = string.Format("VOCHID='" + SingleVocheridSale + "'");
 dataGridview1.DataSource = view;
 object sumObject;
 sumObject = dt.Compute("Sum(NETAMT)", view.RowFilter);
 lable1.Text = sumObject.ToString();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文