c# - 将 Sum 列与另一列相乘

标签 c# mysql sql-server datagridview

我想要一个 SQL 代码从数据库中获取 Product_name,Sum(quantity),price 并将其显示到 winform 上的 datagridview。到目前为止,我有以下代码来获取数据:

conn.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT Prod_name, SUM(quantity) AS quantity, Price FROM Fatur GROUP BY Prod_name, Price ", conn);

DataSet ds = new DataSet();
da.Fill(ds);

dataGridView1.DataSource = ds.Tables[0];
conn.Close();

问题1是:如何在SQL代码中添加另一列乘法 Sum(quantity) * Price AS Total

我尝试了另一种方法,用上面的代码填充dataGridView1,并在dataGridView1中创建另一列,将数量列与价格相乘。这是代码

foreach(DataGridViewRow row in dataGridView1.Rows)
{
    row.Cells[0].Value = Convert.ToString(Convert.ToInt32(row.Cells[2].Value) * Convert.ToInt32(row.Cells[3].Value));
}

但它显示一个空列。

最佳答案

最好用 SQL 来做:

SELECT Prod_name,
  SUM(quantity) AS quantity,
  Price,
  SUM(quantity) * Price total
FROM Fatur
GROUP BY Prod_name,
  Price;

或者:

SELECT prod_name,
  quantity,
  price,
  quantity * price total
FROM
  (SELECT Prod_name,
    SUM(quantity) AS quantity,
    Price
  FROM Fatur
  GROUP BY Prod_name,
    Price
  );

关于c# - 将 Sum 列与另一列相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41469225/

相关文章:

c# - 无需将 DbContext 作为参数传递的 IQueryable 扩展方法

c# - 继承基类时如何避免错误 "Constructor on type ' MyType'not found”

php - mysql_query 在返回时保留在表中创建的数据类型?

mysql - 触发器可以访问在 mysql 中触发它的查询吗

sql-server - SELECT Query 在管理工作室中工作但在 VBA 中不工作

c# - 在 Windows 8/Bing map 应用程序中绘制坐标

c# - 如何在代码隐藏中将 Image.Width 和 Image.Height 重置为自动?

更新后创建 MySQL 触发器

sql - 返回一组列中最高值的最佳实践?

sql-server - SQL Server Management Studio 中的数据库图是否被视为 ER 图?