[英]How to get total quantity of products we have in each warehouse?
I have 3 tables 我有3张桌子
#Products [Pro_ID] ,[Pro_Name],
#Stock [Stock_ID] ,[Pro_ID],[Warehouse_ID] ,[Qty] ,[Status]
Warehouse [Warehouse_ID] ,[Name]
I am making a report for my asp.net project, that shows the total Quantity of products we have in each warehouse. 我正在为我的asp.net项目制作一份报告,其中显示了每个仓库中产品的总数量。 I tried this query which shows nothing except of
Pro_ID
written as header with no data (0 row(s) affected). 我尝试了该查询,该查询什么都没有显示,除了
Pro_ID
写为没有数据的标头(受影响的0行)。
SELECT Pro_ID from Stock
where Qty > 0
GROUP BY Pro_ID
HAVING COUNT(*) = (SELECT COUNT(*) FROM Warehouse)
SELECT
Warehouse.[Warehouse_ID],
Warehouse.[Name]
#Products.[Pro_ID],
#Products.[Pro_Name],
#Stock.[Stock_ID],
#Stock.[Qty],
#Stock.[Status]
FROM
#Stock
LEFT OUTER JOIN Warehouse ON #Stock.[Warehouse_ID] = Warehouse.[Warehouse_ID]
LEFT OUTER JOIN #Products ON #Stock.[Pro_ID] = #Products.[Pro_ID]
Note that by starting with #Stock
and outer joining to the two master tables, you only get results for which you have actual records in the #Stock
table. 请注意,通过从
#Stock
开始和外部#Stock
到两个主表,您只会获得在#Stock
表中具有实际记录的#Stock
。 If you wanted all products at all warehouses, you would select FROM Warehouse CROSS JOIN #Products
to get every combo of product and warehouse, then outer join that to your #Stock
table to get records where they exist, and use null substitution to plug zeroes where you had no record in your #Stock
table. 如果要在所有仓库中使用所有产品,则可以选择
FROM Warehouse CROSS JOIN #Products
以获取产品和仓库的每个组合,然后将其外部#Stock
到#Stock
表中以获取它们存在的记录,并使用空替代插入零。您在#Stock
表中没有记录的#Stock
。
Try this: 尝试这个:
SELECT COUNT(*) from Stock s
INNER JOIN Warehouse w ON s.warehouse_id = w.warehouse.id
where s.Qty > 0
GROUP BY Pro_ID
Your question is a little unclear. 您的问题还不清楚。 Are you looking for a product count by each product in each warehouse?
您要按每个仓库中的每个产品查找产品数量吗? If so, this query should work for you:
如果是这样,此查询将为您工作:
SELECT
warehouse_id, pro_id, SUM(qty) AS quantity
FROM #stock
WHERE Qty > 0
GROUP BY
warehouse_id, pro_id
if you just want to get what is in each warehouse: 如果您只想获取每个仓库中的物品,请执行以下操作:
SELECT w.Name, sum(s.Qty)
FROM Stock s
INNER JOIN Warehouse w
ON s.Warehouse_ID = w.Warehouse_ID
GROUP BY w.Warehouse_ID,w.Name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.