-- Este script se debe ejecutar para los clientes que ya contaban con facturación  y se les agregó el campo para guardar la sede ne la factura
UPDATE  facturas
SET id_headquarter_f  = sedexfactura.id_headquarter
from
(select head.id_headquarter,foa.id_factura
from internal_order io
inner join appointment app on io.internal_order_code= app.internal_order_code
inner join room_appointment_study_receipt rasr  on  app.appointment_code= rasr.appointment_code
inner join room r on rasr.room_code= r.room_code
inner join headquarter head  on r.id_headquarter= head.id_headquarter
inner join (select fo.id_orden, fa.id_factura from facturas fa
inner join facturas_ordenes fo on fa.id_factura =  fo.id_factura
where   fa.id_headquarter_f  is  null
) as foa on io.internal_order_code= foa.id_orden

group by foa.id_factura,head.id_headquarter
order by head.id_headquarter 
)as sedexfactura
where facturas.id_factura= sedexfactura.id_factura
