I have a table (let’s say, prod_config) with the below data-
Prod_Id | Config_Id | Config_Type |
---|---|---|
9856 | 1 | 2 |
9855 | 93 | 1 |
9855 | 92 | 2 |
9855 | 91 | 2 |
9854 | 93 | 1 |
9854 | 92 | 2 |
9854 | 91 | 2 |
9849 | 93 | 1 |
9849 | 92 | 2 |
9850 | 91 | 2 |
9852 | 88 | 1 |
9852 | 90 | 2 |
9853 | 100 | 2 |
The relation is in such a way that —
-
Prod_Id can be mapped to a single or multiple Config_Ids (of Config_Type 1 or 2)
-
If ProdId have single occurence, then ConfigType will always be 2
-
If ProdId have multiple occurence, there will be only single row with ConfigType as 1
I need to find the below result having–
-
all ProdIds having single occurrence
-
For all ProdIds having multiple occurrences, select only the row with Config_Type as 1
Prod_Id | Config_Id | Config_Type |
---|---|---|
9856 | 1 | 2 |
9855 | 93 | 1 |
9854 | 93 | 1 |
9849 | 93 | 1 |
9850 | 91 | 2 |
9852 | 88 | 1 |
9853 | 100 | 2 |
4
Answers
You can use multiple window functions to get your required result –
FIDDLE
The subquery
t2
selects the minimum
Config_Id
for each
Prod_Id
where
Config_Type=1
.
If there are no rows with
Config_Type=1
for a given
Prod_Id
, then the subquery selects the row with the minimum
Config_Id
.
The outer query joins the original table with the subquery on both
Prod_Id
and
Config_Id
.
Prod_Id
is null in the joined result, which means those are not part of the final result
Here is one fairly easy to understand:
But on further thought, as there can be only one config_type=1 existing for a given multiple-instance prod_id, we can simplify it to :
You could achieve your desired output using below query
See demo here