Skip to content
Advertisement

SQL From the same table find records shared by common criteria

DB: postgres (PostgreSQL) 10.16 (Ubuntu 10.16-0ubuntu0.18.04.1)

I have a table device_clients in which following data is present:

id device_id client_id
1 1 1
2 2 1
3 3 1
4 4 1
5 5 1
6 6 1
7 7 1
8 8 1
9 1 2
10 1 3
11 1 4
12 2 2
13 2 3
14 2 4
15 3 2
16 3 3
17 3 4

I need to find out devices common between each client I provide. For e.g. following are the devices for each client

Client-1 => 1, 2, 3, 4, 5, 6, 7, 8
Client-2 => 1, 2, 3
Client-3 => 1, 2, 3
Client-4 => 1, 2, 3

So for clients 1, 2, 3 the common devices expected are 1, 2, 3.

Can anybody please help me formulate an efficient query to achieve the desired results?

Advertisement

Answer

You can use aggregation. For instance:

select device_id
from t
where client_id in (1, 2, 3)
group by device_id
having count(*) = 3;

For convenience, you can pass the list of clients in as an array, allowing you to use:

select device_id
from t
where client_id = any(:client_ar)
group by device_id
having count(*) = cardinality(:client_ar)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement