简体   繁体   中英

How to get total quantity of products we have in each warehouse?

I have 3 tables

#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. I tried this query which shows nothing except of Pro_ID written as header with no data (0 row(s) affected).

SELECT Pro_ID from Stock
where Qty > 0
GROUP BY Pro_ID
HAVING COUNT(*) = (SELECT COUNT(*) FROM Warehouse)

This is what i have recently in stock 库存表

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM