Q:

How do you return col2 where col3 share/overlap col2?

My goal is to have a Rails Active Record Query or SQL Query that takes two variable USER_IDs and returns all, as unique, of the ORG_IDs where those USER_IDs share/overlap a ORG_ID. By as unique, I mean instead of returning [8,8] for below, it would just return 8.
+-------------------------+
| ID   | ORG_ID | USER_ID |
+-------------------------+
|  "51" |   "8"  |  "51"  |
|  "52" |   "8"  |  "52"  |
+-------------------------+

I would like to figure out how to query my TABLE with 51 and 52 as variables for USER_ID that return 8 from ORG_ID. In the above example, I would like to return 8.
+------------------------+
|  ID | ORG_ID | USER_ID |
+------------------------+
| "1" |   "5"  |  "1"    |
| "2" |   "2"  |  "2"    |
| "3" |   "3"  |  "3"    |
| "4" |   "2"  |  "4"    |
| "5" |   "3"  |  "9"    |
| "6" |   "1"  |  "10"   |
| "7" |   "2"  |  "9"    |
| "8" |   "2"  |  "10"   |
| "9" |   "3"  |  "9"    |
| "10"|   "3"  |  "10"   |
+------------------------+

In the next above example, I would like to use 9 and 10 as variables for USER_ID which would match/overlap for ORG_IDs 2 and 3 to return [2,3] in the Ruby Method.
I would like to learn how to do this with active record queries with Rails or SQL. I currently use PostGreSQL 10 for my Database and all values above are bigints. I'm using Rails 5.2.

A:

If I get the point you should pluck columns where user_id is 9 or 10, then manipulate the array. Or maybe thare is a straight query. Anyway this is one possibility.
Model.where(....).pluck(:id, :org_id, :user_id)

Let's say this is the pluck result:
pluck_query_result.map!{ |e| e[1..2] }.group_by{ |e| e[0] }.reject{ |_, v| v.size < 2 }.keys

You can do:
pluck_query_result.map! { |e| e[1..2] }.group_by {|e| e[0]}.reject{ |_, v| v.size < 2}.keys
# => [3, 2]

