| Author |
Topic |
|
paramu
Posting Yak Master
151 Posts |
Posted - 2010-01-24 : 01:23:33
|
| I have 4 tables, having the value of unitprice field need to compare with eachothers "unitprice" and need to findout the latest unitprice from the date field of each other tables.ItemMasteritem_code,unitprice,price_Dateaaa1 70 27/12/2009aaa2 80 01/01/2010aaa3 60 01/01/2010.....GoodsReceiptrec_date, item_code,unitprice15/01/2010,aaa2,6505/01/2010,aaa3,5502/01/2010,aaa2,7011/01/2010,aaa2,75ItemRequestreqs_date,item_code,unitprice06/01/2010,aaa3,65Im_Rq_Amendmentamend_date,item_code,unitprice06/01/2010,aaa3,75From the above tables, I need the select or update the ItemMaster, the data has to be...ItemMasteritem_code,unitprice,price_dateaaa1 70 27/12/2009aaa2 65 15/01/2010aaa3 75 06/01/2010.....ThanksParamu @ PARANTHAMAN |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2010-01-24 : 10:02:03
|
| [code]select im.item_code,t.unitprice,t.price_Datefrom ItemMaster imcross apply (select top 1 unitprice,price_Date from (select unitprice,price_Date,0 as ord from GoodsReceipt where item_code=im.item_code union all select unitprice,price_Date,0 from ItemRequest where item_code=im.item_code union all select unitprice,price_Date,1 from Im_Rq_Amendment where item_code=im.item_code )r order by price_Date desc,ord desc )t[/code] |
 |
|
|
paramu
Posting Yak Master
151 Posts |
Posted - 2010-01-25 : 00:47:34
|
| Thanks For The Wonderful Ideas...!!!Paramu @ PARANTHAMAN |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2010-01-25 : 06:33:17
|
welcome |
 |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2010-01-25 : 06:55:04
|
This is an excellent example of how to use the new MERGE command.--BeforeSELECT *FROM @ItemMaster-- Solution;WITH cteYak(theCode, thePrice, theDate, recID)AS ( SELECT theCode, thePrice, theDate, ROW_NUMBER() OVER (PARTITION BY theCode ORDER BY theDate DESC, thePrice DESC) AS recID FROM ( SELECT item_code AS theCode, unitprice AS thePrice, rec_date AS theDate FROM @GoodsReceipt UNION ALL SELECT item_code, unitprice, reqs_date FROM @ItemRequest UNION ALL SELECT item_code, unitprice, amend_date FROM @im_rq_amendment ) AS d)MERGE @ItemMaster AS tgtUSING ( SELECT theCode, thePrice, theDate FROM cteYak WHERE recID = 1 ) AS src ON src.theCode = tgt.Item_CodeWHEN MATCHED THEN UPDATE SET tgt.UnitPrice = src.thePrice, tgt.Price_Date = src.theDateWHEN NOT MATCHED BY TARGET THEN INSERT ( Item_Code, UnitPrice, Price_Date ) VALUES ( src.theCode, src.thePrice, src.theDate );-- AfterSELECT *FROM @ItemMaster N 56°04'39.26"E 12°55'05.63" |
 |
|
|
|
|
|