我想要一个 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/