SQL Query从表中选择最流行的数据

时间:2015-12-01 19:28:19

标签: sql oracle

我想从此表中选择最常用的名称 Peter

我该怎么做?我尝试过不同的SQL查询,但都没有。

SQL> select * from OurStaffs;

   SID S_LOCATION S_SITE  S_RAN S_NAME
------ ---------- ------- ----- ----------
     1 hotel      root1   rank1 Peter
     2 barbeach   root3   rank0 John
     3 island     root2   rank2 peter
     4 hotel      root2   rank0 ujah

选择了11行。

3 个答案:

答案 0 :(得分:2)

如果你区分大小写,那么就像:

SELECT
   S_NAME,
   count() AS cnt 
FROM
   OurStaffs 
GROUP BY
   S_NAME 
ORDER BY
   cnt DESC
LIMIT 1;

如果您希望不区分大小写,请将S_NAME替换为tolower(S_NAME)lower(S_NAME)等内容,具体取决于您使用的DBMS。对于Oracle,它应该是:

SELECT
   lower(S_NAME),
   count() AS cnt 
FROM
   OurStaffs 
GROUP BY
   lower(S_NAME)
ORDER BY
   cnt DESC 
LIMIT 1;

(当然,upper()会得到相同的结果。)

答案 1 :(得分:1)

我假设SQL加上Oracle ..试试这个 - 它也说明了区分大小写。

With OurStaffs AS
(
      Select 1 SID , 'hotel' S_LOCATION, 'root1' S_SITE, 'rank1' S_RAN, 'Peter' S_NAME From Dual
Union Select 2, 'barbeach', 'root3', 'rank0', 'John' From Dual
Union Select 3, 'island', 'root2', 'rank2', 'peter' From Dual
Union Select 4, 'hotel', 'root2', 'rank0', 'ujah' From Dual
)

Select *
From
(
  Select Upper (S_Name) S_Name, Count(*)
  From OurStaffs
  Group By Upper (S_Name)
  Order by 2 Desc
)x
Where RowNum = 1

答案 2 :(得分:0)

您可以按名称分组,然后按计数排序。这是一个例子:

SELECT
   S_NAME
FROM
    OurStaffs
GROUP BY
    S_NAME
ORDER BY
    COUNT(S_NAME) DESC
LIMIT 1