I want to add to table A informations in table B only for the rows of table A having one and only one row match in table B.
Example : GIVEN table A
+ lastName firstName
+ A B
+ C D
+ E F
AND table B
* lastName firstName age
* A B 10
* C D 15
* C D 20
I WANT TABLE RESULT
* lastName firstName age
* A B 10
* C D null
* E F null
Is it possible to do it in SQL? left join is not sufficient
Kind of
select A.lastName, A.firstName, u.age
from A
left join (
select lastName, firstName, max(age) age
from B
group by lastName, firstName
having count(*) = 1 -- or may be count(distinct age) = 1
) u on u.lastName = A.lastName and u.firstName = A.firstName
I think you want to add unique rows in B
to A
. For this, I would suggest UNION ALL
:
select firstname, lastname, max(age) as age
from b
group by firstname, lastname
having count(*) = 1
union all
select firstname, lastname, null as age
from a
where not exists (select 1
from from b
group by firstname, lastname
having count(*) = 1
);
This should, at least, produce the results in your question.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.