Answer the question
In order to leave comments, you need to log in
UPDATE one field grouped by parent and condition?
Good day!
There was a small problem. There are two tables: organization (id, name), address (id, name, primary, organizationfk). One organization has several addresses and of all, only one is the main one. If the organization has one address, then by default it is the main one.
The problem is that at this stage, due to human error, one organization has several main addresses.
You can help to make a request, which would mark only one of all the addresses of the organization as the main one. But there is one more thing, it is necessary that if an organization has only one main one, then this organization and its addresses should not be touched (they are valid and filled in by users). You need to change only those addresses that are tied to the same organization, but among them, there are several main ones.
Answer the question
In order to leave comments, you need to log in
Will leave only one primary address for the organization.
update address a
set a."primary" = q1.is_primary
from (
select
id
,(row_number() over (partition by organizationfk order by nullif("primary", false))) = 1 is_primary
from address
) q1
where q1.id=a.id
Something like this, but it's better to check on a copy first
UPDATE `address` AS `a1`
JOIN (
SELECT MIN(`id`) AS `id` FROM `address` GROUP BY `organizationfk`
) AS `a2` ON `a2`.`id` = `a1`.`id`
LEFT JOIN (
SELECT `organizationfk` FROM `address` WHERE `primary` = 1
) AS `a3` ON `a3`.`organizationfk` = `a1`.`organizationfk`
SET `a1`.`primary` = 1
WHERE `a3`.`organizationfk` IS NULL
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question