问题
I have a table where there is a PrimaryKey, Foreign Key. I just want to find the list of one Primary per Foreign Key. Example
I need a query that returns only Primary Keys (1 or 2 or 3) and (4 or 5) or (6 or 7 or 8) Essentially 1,4 and 6. How can I get just one PK for each Foreign key
回答1:
Use aggregation:
select foreignKey, min(primaryKey)
from t
group by foreignKey;
If you want a random value, you can use the keep
syntax:
select foreignKey,
min(primaryKey) keep (dense_rank first order by dbms_random.random)
from t
group by foreignKey;
And if you had many columns, you could use row_number()
or a correlated subquery:
select t.*
from t
where t.primarykey = (select min(t2.primarykey) from t t2 where t2.foreignkey = t.foreignkey);
来源:https://stackoverflow.com/questions/64904626/oracle-sql-how-to-find-just-record-from-a-group