我如何得到一个列的和,其中另一个列的项目值=一个值

本文关键字:一个 另一个 项目 何得 | 更新日期: 2023-09-27 17:54:54

我的代码:

string hweight = "Hunters";
string hsql = "SELECT SUM(Weight), Product From Opened WHERE Product =" + hweight;
OleDbCommand hcmd = new OleDbCommand(hsql,conn);
txtHunters.Text = hcmd.ExecuteScalar().ToString();

然后我收到以下错误:

您试图执行一个不包含指定表达式"Product"作为聚合函数一部分的查询。

我如何得到一个列的和,其中另一个列的项目值=一个值

您尝试选择字段/列并同时使用聚合函数,只有当您为所选字段/列提供group by子句时才有效:

string hsql = "SELECT SUM(Weight), Product FROM Opened WHERE Product ='" + hweight + "' GROUP BY Product";

你的SQL应该是:

SELECT SUM(Weight), Product From Opened WHERE Product =" + hweight + " GROUP BY Product"

当你使用聚合函数时,你应该按某些东西对它们进行分组!在您的情况下,产品字段!

试试这个,

string hweight = "Hunters";
string hsql = "SELECT SUM(Weight), Product From Opened WHERE Product =" + hweight + " GROUP BY Product";
OleDbCommand hcmd = new OleDbCommand(hsql,conn);
txtHunters.Text = hcmd.ExecuteScalar().ToString();