简体   繁体   中英

select rows with non distinct values in column 1 scoped to column 2

So i have a people table and bank_accounts table:

People
id | name
1    John
2    Mark
3    Mary

BankAccount
id | person_id | currency
1      1          'USD'
2      1          'EUR'
3      2          'USD'
4      2          'USD'
5      3          'EUR'

I want to get back all accounts with their owners if that owner has only accounts with max one kind of currency. I don't want to get back any account which is owned by user which has another account in another currency. erm :P

so the table i want to get back looks like that:

account_id | person_id | currency

3            2(Mark)     'USD'
4            2(Mark)     'USD'
5            3(Mary)     'EUR'

Hope it's understandable. This is simplified example of course. I will use this on a lot bigger tables with a lot of data. So some efficiency would be also good.

Thanks a lot for your time and help!

select * 
from bankAccount
where person_id in
(
  select person_id
  from bankAccount
  group by person_id
  having count(distinct currency) = 1
)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM