I have the following data in a simple table:
ID | TYPE
---------
1 | 1
1 | 2
2 | 1
3 | 2
4 | 1
4 | 2
4 | 3
5 | 1
5 | 3
6 | 3
I now need to query this data in the following way:
- For each ID, only one row should be returned
- If there is only one row for the ID return it.
- If there are multiple rows for the ID, return the one with TYPE = 2. If that doesn’t exist, return the one with TYPE = 3.
- TYPE can be either 1, 2 or 3
- ID and TYPE have a composite unique index, meaning that per ID there can be a maximum of three rows.
Question: How would I put this logic in a query?
Expected result:
ID | TYPE
---------
1 | 2
2 | 1
3 | 2
4 | 2
5 | 3
6 | 3
Oracle has analytic functions in all recent versions.
With this technique you will return all the values in the table, rather than just the PrimaryKey and the search value.
EDIT:
The best way of dealing with that is to have another table that has the order of preference for each type.
This states that
2is the most preferential,3is the second preference, and1is the third preference.Because it’s such a small group, however, it can also be done just with a simple
CASEstatement. See my amended query above.