Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
Nls
Starting Member
2 Posts |
Posted - 2009-09-25 : 17:31:34
|
| Hello, thanks but I am not quite sure I understand it.Let me take a new example.I have 4 tables:ItemsOrdersPurchaseWarehouseI want to sum, for every item in itemstable, quantity in orders, purchase and warehousetable.I believe there must be a derived table involved but I'm not sure about the syntaxSee attached image for an explanation with tabledata.[url]http://www.tomasbredh.se/tables.jpg[/url] |
|
|
rekiller
Starting Member
31 Posts |
Posted - 2009-09-25 : 18:25:21
|
| [code]DECLARE @ITEMS TABLE (ItemNumber Char(1))DECLARE @ORDERS TABLE (ItemNumber Char(1), Quantity Integer)DECLARE @PURCHASE TABLE (ItemNumber Char(1), Quantity Integer)DECLARE @WAREHOUSE TABLE (ItemNumber Char(1), Quantity Integer)INSERT INTO @ITEMSSELECT 'A'UNIONSELECT 'B'UNIONSELECT 'C'INSERT INTO @ORDERSSELECT 'B',4UNIONSELECT 'A',1UNIONSELECT 'A',3UNIONSELECT 'C',6UNIONSELECT 'B',2INSERT INTO @PURCHASESELECT 'B',6UNIONSELECT 'B',2UNIONSELECT 'C',4UNIONSELECT 'C',33UNIONSELECT 'A',1INSERT INTO @WAREHOUSESELECT 'A',4UNIONSELECT 'A',1UNIONSELECT 'A',3UNIONSELECT 'C',6UNIONSELECT 'B',3SELECT A.ItemNumber, ISNULL(( B.Quantity ),0) QOrders, ISNULL(( C.Quantity ),0) QPurchase, ISNULL(( D.Quantity ),0) QWareHouseFROM @ITEMS ALEFT JOIN (SELECT ItemNumber, SUM(Quantity) Quantity FROM @ORDERS GROUP BY ItemNumber) B ON A.ItemNumber = B.ItemNumbeRLEFT JOIN (SELECT ItemNumber, SUM(Quantity) Quantity FROM @PURCHASE GROUP BY ItemNumber) C ON A.ItemNumber = C.ItemNumbeRLEFT JOIN (SELECT ItemNumber, SUM(Quantity) Quantity FROM @WAREHOUSE GROUP BY ItemNumber) D ON A.ItemNumber = D.ItemNumbeR[/code] |
 |
|
|
Nls
Starting Member
2 Posts |
Posted - 2009-09-26 : 13:39:22
|
| Works great! Thanks alot! |
 |
|
|
|
|
|
|
|