2013-11-15 59 views
-1

我有2个表,'Items'和'Itemldgr'。我想使用itemldgr的最新itemldgr.purchaseprice更新items.salepriceSQL 2008 - 使用另一个表的最新日期从其他表更新表

这有点平原的想法:

update items set items.saleprice = (itemldgr.purchaseprice * 1.30) from itemldgr, 
items 
where items.itemid = itemldgr.itemid 
and itemldgr.docdate = (
select itemldgr.itemid,MAX(docdate) 
from itemldgr 
where itemldgr.docid = 'RR' 
and itemldgr.netcost <> '0' 
and itemldgr.qtyin <> '0' 
group by itemldgr.itemid 
order by itemid)` 

回答

1

试试这个

update items 
    INNER JOIN itemldgr on items.itemid = itemldgr.itemid 
    set items.saleprice = itemldgr.purchaseprice * 1.30 , 
    where itemldgr.docdate = (
          select itemldgr.itemid,MAX(docdate) 
          from itemldgr 
          where itemldgr.docid = 'RR' 
          and itemldgr.netcost <> '0' 
          and itemldgr.qtyin <> '0' 
          group by itemldgr.itemid 
          order by itemid) 
1

通过选择更新的时候,尽量做到在以下方面:

UPDATE a 
Set a.Column1 = b.Column2 
FROM Table a 
INNER JOIN Table b ON a.ID = b.aID 

它一个简单的方法, 为您的查询它会变成这样的:

update b 
    set b.saleprice = (a.purchaseprice * 1.30) 
from 
     itemldgr a 
inner join items b ON a.itemid = b.itemid 
WHERE a.docdate = 
(
    select MAX(docdate) 
    from itemldgr c 
    where c.docid = 'RR' 
    and c.netcost <> '0' 
    and c.qtyin <> '0' 
    and c.itemid = a.itemid 
)