我有三张桌子产品,购买和销售
Product
Item_code Item_Name
1 Panadol
2 Disprin
3 Calpol
4 Arinac
Purchase
Item_code Pur_Item_PackQuantity
1 5
1 4
3 5
4 6
Sale
Item_code Item_Sale_Quantity
1 5
1 4
3 5
4 6
现在我想从Product表中获取所有Item_name,并从Sale and Purchase表中获取Sale.Item_Sale_Quantity + Purchase.Pur_Item_PackQuantity的总和,但我正在尝试给出以下查询产生错误
string query = "SELECT Product.Item_Name,Product.Packing,Product.MRP,SUM(Purchase.Pur_Item_PackQuantity)-SUM(Sale.Item_Sale_Quantity)AS[Stock] FROM Purchase RIGHT JOIN Product ON Product.Item_Code = Purchase.Item_Code Group By Item_Name ORDER BY Item_Name ";
SqlConnection newcon = new SqlConnection("Data Source=.;Initial Catalog=mateenwin;User ID=sa;Password=123");
SqlCommand newcommand = new SqlCommand(query, newcon);
SqlDataAdapter dp = new SqlDataAdapter(newcommand);
DataTable dttt = new DataTable();
dp.Fill(dttt);
dataGridView3.DataSource = dttt;
请帮我解决此问题
答案 0 :(得分:0)
这是一个SQL查询修复。
select p.Item_Code, p.Item_Name, p.[Total],s.[Sold], p.Total - s.Sold as [Stock]
from (select pro.Item_Code, pro.Item_Name,sum(pur.Pur_Item_PackQuantity) as [Total]
from product pro left outer join purchase pur on pro.Item_code = pur.Item_Code
group by pro.Item_Code,pro.Item_Name) as p
join (select pro.Item_Code ,sum(s.Item_Sale_Quantity) as [Sold]
from product pro left outer join sale s on pro.Item_Code = s.Item_Code
group by pro.Item_Code) as s
on p.Item_Code = s.Item_Code
order by p.Item_Code asc
答案 1 :(得分:0)
您需要将查询更改为:
string query = "
SELECT Product.Item_Name, Product.Packing,
Product.MRP,SUM(Purchase.Pur_Item_PackQuantity)-SUM(Sale.Item_Sale_Quantity)
AS [Stock]
FROM Purchase RIGHT JOIN Product ON Product.Item_Code = Purchase.Item_Code
Group By Item_Name,Packing,MRP
ORDER BY Item_Name
";