Oracle SQL : how to find just record from a group

梦想与她 提交于 2021-02-11 13:12:28

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!