如何找到最常用和最少使用的键?

时间:2015-08-07 18:46:29

标签: sql oracle

我的表中有这些数据:

INSERT INTO VIDEOS VALUES(20,'V1','KIDNAP','CRIME');
INSERT INTO VIDEOS VALUES(20,'V2','ABUSE','CRIME');
INSERT INTO VIDEOS VALUES(20,'V3','ROBBERY','CRIME');
INSERT INTO VIDEOS VALUES(20,'V4','MURDER','CRIME');
INSERT INTO VIDEOS VALUES(20,'V5','POLITICAL','POLITICAL');
INSERT INTO VIDEOS VALUES(20,'V6','POLITICAL','POLITICAL');
INSERT INTO VIDEOS VALUES(20,'V7','POLITICAL','POLITICAL');
INSERT INTO VIDEOS VALUES(20,'V8','POLITICAL','POLITICAL');
INSERT INTO VIDEOS VALUES(20,'V9','SOCIAL','SOCIAL');
INSERT INTO VIDEOS VALUES(19,'V1','KIDNAP','CRIME');
INSERT INTO VIDEOS VALUES(19,'V2','ABUSE','CRIME');
INSERT INTO VIDEOS VALUES(19,'V3','ROBBERY','CRIME');
INSERT INTO VIDEOS VALUES(19,'V4','MURDER','CRIME');
INSERT INTO VIDEOS VALUES(19,'V5','POLITICAL','POLITICAL');
INSERT INTO VIDEOS VALUES(19,'V6','POLITICAL','POLITICAL');
INSERT INTO VIDEOS VALUES(19,'V7','POLITICAL','POLITICAL');
INSERT INTO VIDEOS VALUES(19,'V8','POLITICAL','POLITICAL');
INSERT INTO VIDEOS VALUES(29,'V1','KIDNAP','CRIME');
INSERT INTO VIDEOS VALUES(29,'V2','ABUSE','CRIME');
INSERT INTO VIDEOS VALUES(29,'V3','ROBBERY','CRIME');

从上面的19,20和29是关键值。我想找到具有最小和最大数值以及键的键。

此处键29具有最少的值(3),键20具有最多的值(9)。

如何识别最少和最常用的键值?

1 个答案:

答案 0 :(得分:3)

如果您没有联系,则可以使用keep dense_rank或其中的两个版本,使用firstlast

select min(id) keep (dense_rank first order by count(*)) as id_with_fewest,
  max(id) keep (dense_rank last order by count(*)) as id_with_most
from videos
group by id;

ID_WITH_FEWEST ID_WITH_MOST
-------------- ------------
            29           20

如果您确实有联系,可以通过向order by添加另一个条款来决定如何订购 - 说order by count(*), id

如果存在平局,此方法将不允许您返回两个结果。如果您需要这样做,您可以使用inine视图。添加一些数据,以便计算最低数量:

INSERT INTO VIDEOS VALUES(30,'V1','KIDNAP','CRIME');
INSERT INTO VIDEOS VALUES(30,'V2','ABUSE','CRIME');
INSERT INTO VIDEOS VALUES(30,'V3','ROBBERY','CRIME');

最小

select id
from (
  select id, dense_rank() over (order by count(*)) as rnk
  from videos
  group by id
)
where rnk = 1;

        ID
----------
        30
        29

最大:

select id
from (
  select id, dense_rank() over (order by count(*) desc) as rnk
  from videos
  group by id
)
where rnk = 1;

        ID
----------
        20