sql 显示求和结果

sql diplay sum result

如何将查询的总和结果显示到以下网格视图中:

string raf5 = string.Format("select SUM(orderDetails.unitPrice) from orderDetails INNER JOIN Orderz ON orderDetails.orderId=Orderz.Id AND Orderz.customerId={0} ", k);
SqlCommand comm5 = new SqlCommand(raf5, c);
SqlDataReader r55 = comm17.ExecuteReader();
DataTable ts = new DataTable();
ts.Columns.Add("Total Sum", typeof(string));
while (r55.Read())
{
    ts.Rows.Add(r55["unitPrice"].ToString());
}
c.Close();
GridView3.DataSource = ts;
GridView3.DataBind();

您遇到的问题是缺少列名。 您需要像这样为总和指定一个列名:

string raf5 = string.Format("select SUM(orderDetails.unitPrice) as unitPrice from orderDetails INNER JOIN Orderz ON orderDetails.orderId=Orderz.Id AND Orderz.customerId={0} ", k);

或者,您可以通过数据中的索引获取列 reader:

ts.Rows.Add(r55[0].ToString());

此外,您返回的是单个值,因此最好使用 (decimal)com17.ExecuteScalar()