简体   繁体   中英

to display all records from one table and sum of rows from another table

I have two tables HouseKeeping with fields RoomNo,FloorNo,StockItem,Requirement and Stock table with fields Item ,Available.I want to select all rows from HouseKeeping table and sum of requirement from stock table.I have used this query to get sum of requirement from stock table

SELECT SUM(Requirement) AS Requirement, StockItem FROM HouseKeeping GROUP BY StockItem

in addition to this i also want all records(select * from Stock).How to do it? please reply as soon as possible.Thanks

If I understand you correctly:

JOIN the two tables like so:

SELECT h.stockItem, SUM(h.Requirement)
FROM HouseKeeping h 
INNER JOIN Stock s ON h.stockItem = s.Item
GROUP BY h.stockItem

This will give you all the sum of all the Requirement values for only the item that has a Requirement in the other table stock .

If you want to include those non matching items, ie: with no item in the stock table. Use a LEFT JOIN instead of the INNER JOIN with ISNULL(SUM(h.Requirement) to set a 0 instead of NULL .

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