如何获取另一列项目值=值的列的总和?

时间:2015-06-09 11:22:17

标签: c# sql ms-access

我的代码:

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();

然后我收到以下错误:

  

您尝试执行的查询不包含指定的表达式'产品'作为集合函数的一部分。

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

你的SQL应该是:

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

当您使用聚合函数时,您应该按某种方式对它们进行分组!在你的情况下,产品领域!

答案 2 :(得分:0)

试试这个,

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();