Skip to content
Advertisement

UPDATE column based on whether it has NULL in a grouping

This might be very simple question, but I just can’t come up with a solution.

Here is an example

Key1 is unique. We set Key3 by using following logic:

Table looks like this

enter image description here

I want Key4 to be:

Since any particular Key3 grouping has Key4 values all NULL, set it to Key3. Result should be this

enter image description here

Now, assume adding 1 more row:

And then we run UpdateKey3 query, result would become:

enter image description here

Now, we need to **** query, that will update Key4. Since new row is in Key3 group = 1004, and we already have previously filled Key4 for that group, NULL should become 1002. Final result

Aka, once we set Key4 for any particular Key3 grouping, Key4 should never change. What would be that **** query?

enter image description here

Advertisement

Answer

It’s a little hard to follow, but I think I see what you’re saying:

If key4 is null …

  • Try to find another record with the same key3 value, and see what it says for key4.
  • If any such record has a key4 value, use it
  • Else just use the current record’s key 3 value

With this in mind, to update Key 4, you might want a procedure like this:

I stress ‘might’ because your statement (which I translated into the second bullet above):

Since new row is in Key3 group = 1004, and we already have previously filled Key4 for that group, NULL should become 1002.

doesn’t take into consideration the possibility that two previously existing key 3 groups of 1004 might have different key 4 values. Yes, in your example they’re both 1002, but in the future they won’t always be.

You’ll have to choose between one of them, and it’s not clear which one to choose. You’ll really have to nail that down before you put any such code into production.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement