Table: Dummy
|Colum1 | Colum2 |
|:------|:-------|
| 219 | 217 |
| 219 | 218 |
| 228 | 218 |
| 228 | 225 |
| 229 | 218 |
| 229 | 220 |
I need result set where if user provided numbers in where clause should exactly match along with its count example. if user sends where ( 217,218 ) then it should return with colum1 has value 219.
Following queries is returning the result set as below.
SELECT *
from Dummy
GROUP BY Colum1
having count(distinct Colum2 ) = 2 and Colum2 in (217, 218);
| 219 | 217 |
| 228 | 218 |
| 229 | 218 |
required output:
| 219 | 217 |
The no of distinct Colum2 is dynamic , it can be 2 ,3 ,4 or 5.
4
Answers
You could just join the table back on its self
You need to move the
Colum2
criterion to theWHERE
clause:As pointed out by Aconcagua, you could add a
NOT EXISTS
if you want to include only theColum1
values which do not have any otherColum2
values:Here’s a db<>fiddle
Based on @user1191247‘s answer and assuming you want to get those groups where the list of values of column2 comprises exactly the values
{217, 218}
(none less, none more) then the following query can give you the desired result:The basic idea of is: The self-join assures we have column2 duplicated, then we can filter out all unwanted values within one of the duplicated columns, but leave them in the other. If all wanted values exist the count of the filtered column needs to equal the number of these values – and the count of the unfiltered column needs to alike, otherwise surplus values would exist (note that the latter’s count then would be greater; it cannot ever get smaller, though).
See user1191247’s modified fiddle (only the query for two values is adjusted).
Try using the below query: