我希望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是:如何在乘法 Sum(quantity) * Price AS Total
的SQL代码上添加另一列?
我尝试了用上述代码填充 dataGridView1 的另一种方法,并在 dataGridView1 中创建了另一列,该列乘以 quantity 和价格的列。这是代码
foreach(DataGridViewRow row in dataGridView1.Rows)
{
row.Cells[0].Value = Convert.ToString(Convert.ToInt32(row.Cells[2].Value) * Convert.ToInt32(row.Cells[3].Value));
}
但是它显示了一个空列。
答案 0 :(得分:0)
最好在SQL中执行:
SELECT Prod_name,
SUM(quantity) AS quantity,
Price,
SUM(quantity) * Price total
FROM Fatur
GROUP BY Prod_name,
Price;
OR:
SELECT prod_name,
quantity,
price,
quantity * price total
FROM
(SELECT Prod_name,
SUM(quantity) AS quantity,
Price
FROM Fatur
GROUP BY Prod_name,
Price
);
答案 1 :(得分:0)
尝试在查询中包含计算列,如:
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT Prod_name, SUM(quantity) AS quantity, Price,SUM(quantity)*Price as Total FROM Fatur GROUP BY Prod_name, Price ", conn);
DataSet ds = new DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
conn.Close();