SQL 2008: actualice la tabla desde otra tabla usando la fecha más reciente de la otra tabla

I have 2 tables, 'Items' and 'Itemldgr'. I want to update items.saleprice usando lo último itemldgr.purchaseprice de itemldgr.

This is sort of the plain idea:

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)`

preguntado el 15 de noviembre de 13 a las 08:11

2 Respuestas

prueba este

   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)

respondido 15 nov., 13:08

when updating via selects, try to do it in the following context:

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

it's an easy approach, for your query it would become something like:

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
)

respondido 15 nov., 13:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.