Update a table from another table - sql

I have got 2 tables "animal_breeds" and "ztmp.ztmp_509810_anims_out". In "animals breed" every animal has key and breed name and percentage. Few animals might have 2 different breeds with different percentage. Now based on the animals key in "animals_breeds" i want to update "ztmp.ztmp_509810_anims_out"
i am using this code which i know is wrong
update ztmp.ztmp_509810_anims_out
set
alt_id1 = ab.breed
,alt_id2 = pcnt
,alt_id3 = ab.breed
,alt_id4 = pcnt
,alt_id5 = ab.breed
,alt_id6 = pcnt
,alt_id7 = ab.breed
,alt_id8 = pcnt
from animal_breeds ab
where ab.soc_code = ztmp_509810_anims_out.soc_code and ab.animals_key = ztmp_509810_anims_out.animals_key
and ab.soc_code = 'AUNDB';
could i use a for loop inside an update statement?

UPDATE ztmp.ztmp_509810_anims_out AS z
SET soc_code = q.soc_code,
animals_key = q.animals_key,
alt_id1 = breeds[1],
alt_id2 = pcnts[1],
alt_id3 = breeds[2],
alt_id4 = pcnts[2]
FROM (SELECT soc_code, animals_key,
array_agg(breed) breeds, array_agg(pcnt) pcnts
FROM animal_breeds
GROUP BY soc_code, animals_key
) q
WHERE z.soc_code = q.soc_code
AND z.animals_key = q.animals_key;
If there can be more than 2 breeds per animals_key, add breeds[3] and pcnts[3] and so on.

Related

Update Query Access 2007 Group into one row

I'm playing around with access and vba. I'm struggleing to update and to group rows from tblLoadingListItems into tblLoadSummary using the query below
UPDATE tblLoadSummary INNER JOIN tblLoadingListItems ON (tblLoadSummary.salesno = tblLoadingListItems.salesno) AND (tblLoadSummary.loadnolink = tblLoadingListItems.loadnolink) SET tblLoadSummary.[Cust O/N] = [tblLoadingListItems].[Cust O/N], tblLoadSummary.traderid = [tblLoadingListItems].[traderid], tblLoadSummary.street = [tblLoadingListItems].[street], tblLoadSummary.[zone] = [tblLoadingListItems].[zone], tblLoadSummary.salesno = [tblLoadingListItems].[salesno], tblLoadSummary.[Customer Ref] = [tblLoadingListItems].[Customer Ref], tblLoadSummary.DeliveryAddress = [tblLoadingListItems].[DeliveryAddress], tblLoadSummary.Postcode = [tblLoadingListItems].[Postcode], tblLoadSummary.SumOfnoofpacks = Sum([tblLoadingListItems].[packs1]), tblLoadSummary.SumOfnoofboxes = Sum([tblLoadingListItems].[noofboxes]), tblLoadSummary.contact = [tblLoadingListItems].[contact], tblLoadSummary.telephone = [tblLoadingListItems].[telephone], tblLoadSummary.fax = [tblLoadingListItems].[fax], tblLoadSummary.email =
[tblLoadingListItems].[email], tblLoadSummary.deliverycontact = [tblLoadingListItems].[deliverycontact], tblLoadSummary.deliverytelephone = [tblLoadingListItems].[deliverytelephone], tblLoadSummary.deliveryfax = [tblLoadingListItems].[deliveryfax], tblLoadSummary.deliveryemail = [tblLoadingListItems].[deliveryemail], tblLoadSummary.acknowaddress = [tblLoadingListItems].[acknowaddress]
WHERE (((tblLoadSummary.salesno)="SM-100118") AND ((tblLoadSummary.loadnolink)=32232))
If i show datasheet view i get two rows returned, Im trying to group these rows into one.
When i try to add a GROUP BY after the WHERE i get syntax errors missing operators for all my fields.
Can you someone point me in the right direction?
I am not sure with access but starting update like this and maybe its wrong :
Update tblLoadSummary inner join...
try it like this
update t set .... from tblLoadSummary t inner join tblLoadSummary s on ...
this is the full query
UPDATE t-- tblLoadSummary
SET t.CustO/N = s.CustO/N,
t.traderid = s.traderid,
t.street = s.street,
t.zone = s.zone,
t.salesno = s.salesno,
t.CustomerRef = s.Customer Ref,
t.DeliveryAddress = s.DeliveryAddress,
t.Postcode = s.Postcode,
t.SumOfnoofpacks = Sum(s.packs1),
t.SumOfnoofboxes = Sum(s.noofboxes),
t.contact = s.contact,
t.telephone = s.telephone,
t.fax = s.fax,
t.email = s.email,
t.deliverycontact = s.deliverycontact,
t.deliverytelephone = s.deliverytelephone,
t.deliveryfax = s.deliveryfax,
t.deliveryemail = s.deliveryemail,
t.acknowaddress = s.acknowaddress
from tblLoadSummary as t
INNER JOIN tblLoadingListItems as s ON
(t.salesno = s.salesno) AND (t.loadnolink = s.loadnolink)
WHERE (((t.salesno) = "SM-100118") AND
((t.loadnolink) = 32232))

Avoiding multiple sub queries

I'm trying to update a couple of columns in a table using another record in the same table. Following is the SQL that I came up with but I'm wondering how I can avoid multiple sub queries that will return the same record. I'm working on Oracle 11gR2.
UPDATE
IFTBL E
SET
E.ATT_CREATED = (SELECT A.CREATED FROM ATT A WHERE A.ROW_ID = E.T_ACTIVITYA__RID),
E.ATT_CREATED_BY = (SELECT B.CREATED_BY FROM ATT B WHERE B.ROW_ID = E.T_ACTIVITYA__RID)
WHERE
E.IF_ROW_BATCH_NUM = BATCH_NO_IN AND E.IF_ROW_STAT = 'EXPORTED' AND E.ATT_FILE_SRC_TYPE = 'FILE';
You can use Merge.
MERGE INTO IFTBL
USING
(
SELECT CREATED,CREATED_BY,ROW_ID
FROM ATT
) A ON (A.ROW_ID = IFTBL.T_ACTIVITYA__RID)
WHEN MATCHED THEN UPDATE
SET
IFTBL.ATT_CREATED = A.CREATED,
IFTBL.ATT_CREATED_BY = A.CREATED_BY
WHERE
IFTBL.IF_ROW_BATCH_NUM = BATCH_NO_IN
AND IFTBL.IF_ROW_STAT = 'EXPORTED'
AND IFTBL.ATT_FILE_SRC_TYPE = 'FILE'
If ROW_ID is primary key in ATT and T_ACTIVITYA__RID is foreign key on IFTBL with reference to ROW_ID you may write update (select ...)
update (select E.ATT_CREATED, E.ATT_CREATED_BY
A.CREATED , A.CREATED_BY
from IFTBL E, ATT A
where E.T_ACTIVITYA__RID = A.ROW_ID(+)
AND E.IF_ROW_BATCH_NUM = BATCH_NO_IN
AND E.IF_ROW_STAT = 'EXPORTED'
AND E.ATT_FILE_SRC_TYPE = 'FILE')
SET ATT_CREATED = CREATED,
ATT_CREATED_BY = CREATED_BY ;
In addition to the other answers, you could simply do a multi-column update:
UPDATE
IFTBL E
SET
(E.ATT_CREATED, E.ATT_CREATED_BY) = (SELECT A.CREATED,
A.CREATED_BY
FROM ATT A
WHERE A.ROW_ID = E.T_ACTIVITYA__RID)
WHERE
E.IF_ROW_BATCH_NUM = BATCH_NO_IN
AND E.IF_ROW_STAT = 'EXPORTED'
AND E.ATT_FILE_SRC_TYPE = 'FILE';

Catching last datetime after update wont result

I have the following code:
UPDATE sm
SET sm_fecha_venc = (SELECT MIN(nd_fecha_venc) FROM [db_facturacion].[dbo].[tb_notas_debito]
WHERE sm_codigo = nd_num_servicio
-- AND nd_referencia = sm_cod_producto
AND nd_num_factura = sm_cod_factura
AND nd_estado = 'G')
,sm_fecha_ult_pago = (SELECT MAX(nd_fecha_pago) FROM [db_facturacion].[dbo].[tb_notas_debito]
WHERE sm_codigo = nd_num_servicio
-- AND nd_referencia = sm_cod_producto
AND nd_num_factura = sm_cod_factura
AND nd_estado = 'C')
,sm_fecha = GETDATE()
,sm_cod_factura_ren = #i_num_factura
OUTPUT DELETED.sm_fecha_venc AS FECHA_VENC_OLD,
DELETED.sm_fecha_ult_pago AS FECHA_ULT_PAGO_OLD,
DELETED.sm_fecha AS FECHA_OLD,
DELETED.sm_cod_factura_ren AS COD_FACTURA_REN_OLD
INTO #TABLATABLA --
FROM [db_facturacion].[dbo].[tb_servicios] sm --WITH(NOLOCK)
INNER JOIN #servicios AS T ON sm_codigo = num_servicio
WHERE sm_tipo_bien_protegido = 1
AND [sm_estado] = 1
--AND sm.sm_cod_forma_contrato = 1
AND sm.sm_tipo_inventario = tipo_inventario
/*===========================
INSERTED DELETED
=============================*/
UPDATE db_facturacion.[dbo].[tb_log_cambio_servicio]
SET cs_fecha_venc_old = FECHA_VENC_OLD
,cs_fecha_ult_pago_old = FECHA_ULT_PAGO_OLD
,cs_fecha_old = FECHA_OLD
,cs_cod_factura_ren_old = COD_FACTURA_REN_OLD
FROM #TABLATABLA
WHERE cs_codigo = #ID_ULTIMO_ING (LAST ##IDENTITY)
Im trying to save the last dates into a log table, just in case I have to return those dates back.
The code works good, just that it's catching the actual date and inserted in the log table.
What am I missing?

Linq GROUP BY or manually grouping in a loop?

Yesterday I asked this question on stackoverflow. Today I realize that if I do a GROUP BY I also need to create a new type of object.
Let's say I have some data that looks like this:
var1 var2 var3 qty
1 a 1a 50
1 a 1a 25
2 b 2b 10
2 b 2b 15
2 b 2b 10
3 a 3a 25
Here is my working LinQ query
From j In MyTable
Where j.var1 = "xxx"
Group j By Key = New With {Key .var1 = j.var1, Key .var2= j.var2, Key .var3 = j.var3} Into Group
Select New With {.var1 = Key.var1, .var2 = Key.var2, .var3 = Key.var3, .qty = Group.Sum(Function(x) x.qty)}
Actually I use Entity Framework and the code look more like this
Dim foo = (From j In dbContext.MyTable
Where j.var1 = anotherVariable
Group j By Key = New With {Key .var1 = j.var1, Key .var2= j.var2, Key .var3 = j.var3} Into Group
Select New With {.var1 = Key.var1, .var2 = Key.var2, .var3 = Key.var3, .quantity = Group.Sum(Function(x) x.Qty)}).ToArray()
foo is a new type that doesn't exist in my generated Entities. But I have an entity generated by my entity framework that can contains these. It's MyTable itself. I use a GROUP BY only to sum a column of MyTable. I query a MyTable entities and I can put the result in a MyTable entity too.
My question are
1) Can I write something like this
Dim foo = (From j In dbContext.MyTable
Where j.var1 = anotherVariable
Group j By Key = New With {Key .var1 = j.var1, Key .var2= j.var2, Key .var3 = j.var3} Into Group
Select New MyTable With {.var1 = Key.var1, .var2 = Key.var2, .var3 = Key.var3, .qty = Group.Sum(Function(x) x.qty)}).ToArray()
In this case do I need to explicitely write all the mappings ?
2) Should I change my mind. Do a simpler query without GROUP BY and try to group and sum in a VB.NET loop (For Each). Or two queries ? On to get all MyTable with a WHERE clause and another to group ?
Dim foo = dbContext.MyTable.Where(Function(p As MyTable) p.var1 = anotherVariable).ToArray()
For Each bar In foo
'Code to group and sum or another query
Next
You won't be able to instantiate MyTable in an LINQ to Entities query but you can simply enumerate the results of the projection with ToArray and then construct the entities with another Select call.

linq to sql The Grid view

I make sales and procurement system and when I work a query, or search the invoice number, the results appear in palm leaves View, but appears only in a row while the bill by no more than one row
And this was used by code
i.m used vb.net and database sql and b yway linq to sql
Try
Dim data = (From d In DBVariable.Data.masterfatoras
From f In DBVariable.Data.fatoras
From na In DBVariable.Data.asnafs
From sup In DBVariable.Data.suppliers
Where d.ID = f.mid Where d.num.Contains(txt)
Select d, f, na, sup).FirstOrDefault
TextBoxX1.Text = data.d.num
nammord.Text = (From supp In DBVariable.Data.suppliers Where data.d.idmord = supp.ID Select supp.Name).Single()
txtmord.Text = (From supp In DBVariable.Data.suppliers Where data.d.idmord = supp.ID Select supp.Code).Single()
adrmord.Text = (From supp In DBVariable.Data.suppliers Where data.d.idmord = supp.ID Select supp.Address).Single()
nodaf.Text = data.d.nodfa
' ''نفاصيل الفاتورة
For p As Integer = 0 To gridshraa.Rows.Count - 1
gridshraa.Rows(p).Cells(2).Value = (From asna In DBVariable.Data.asnafs Where data.f.idname = asna.ID Select asna.Name).Single()
gridshraa.Rows(p).Cells(1).Value = (From asna In DBVariable.Data.asnafs Where data.f.idname = asna.ID Select asna.code).Single()
gridshraa.Rows(p).Cells(3).Value = (From asna In DBVariable.Data.asnafs Where data.f.idname = asna.ID Select asna.unit).Single()
gridshraa.Rows(p).Cells(4).Value = data.f.qty
gridshraa.Rows(p).Cells(5).Value = data.f.price
gridshraa.Rows(p).Cells(6).Value = data.f.totprice
Next
Catch
End Try