Pergunta

I have a master table in sql server 2012 that consists of two types.

These are the critical columns I have in my master table:

TYPE    CATEGORYGROUP   CREDITORNAME    DEBITORNAME

One of those two types (Type B) doesn't have a CategoryGroup assigned to it (so it's always null).

Type A always has a CategoryGroup and Debitor.

Type B always has a Creditor but no CategoryGroup.

For creditor and debitor I have two extra tables that also hold the CategoryGroup but for my task I only need the table for creditors since I already have the right value for type A (debitors).

So my goal is to look-up the CategoryGroup in the creditor table based on the creditor name and ideally put those CategoryGroup values in my master table. With "put" I'm not sure if a view should be generated or actually put the data in the table which contains about 1.5 million records and keeps on growing.

There's also a "cluster table" that uses the CategoryGroup as a key field. But this isn't part of my problem here.

Please have a look at my sample fiddle

Hope you can help me. Thank you.

Foi útil?

Solução

If I understand you correctly, you can simply do a join to find the correct value, and update MainData with that value;

You can either use a common table expression...

WITH cte AS (
  SELECT a.*, b.categorygroup cg
  FROM MainData a
  JOIN CreditorList b
    ON a.creditorname = b.creditorname
)
UPDATE cte SET categorygroup=cg;

An SQLfiddle to test with.

...or an UPDATE/JOIN;

UPDATE m
SET m.categorygroup = c.categorygroup
FROM maindata m
JOIN creditorlist c
  ON m.creditorname = c.creditorname;

Another SQLfiddle.

...and always remember to test before running potentially destructive SQL from random people on the Internet on your production data.

EDIT: To just see the date in the same format without doing the update, you can use;

SELECT 
  a.type, COALESCE(a.categorygroup, b.categorygroup) categorygroup,
  a.creditorname, a.debitorname
FROM MainData a
LEFT JOIN CreditorList b
  ON a.creditorname = b.creditorname

Yet another SQLfiddle.

Outras dicas

Couldn't you just do:

update maindata
set categorygroup = (
    select top 1 categorygroup 
    from creditorlist 
    where creditorname = maindata.creditorname)
where creditorname is not null
and categorygroup is null

?

Try this -

update m
set m.CategoryGroup = cl.CategoryGroup
-- select m.creditorName, 
-- m.CategoryGroup as Dest, 
-- cl.CategoryGroup as Src
from maindata as m
left join creditorlist as cl
on m.creditorName = cl.creditorName
where m.creditorName is not null

Before you update, you can check the results of the query by uncommenting the update statement and removing the updates.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top