Table 根据特定项目的出现次数排序

Table sorting based on the number of occurrences of a particular item

这是一个包含 2 列的示例 table。

 id | name
------------
  1 | hello  
  2 | hello  
  3 | hello  
  4 | hello  
  5 | world  
  6 | world  
  7 | sam  
  8 | sam  
  9 | sam  
 10 | ball  
 11 | ball  
 12 | bat  
 13 | bat  
 14 | bat  
 15 | bat  
 16 | bat 

上面table这里是出现次数

hello  - 4  
world  - 2  
sam    - 3  
ball   - 2  
bat    - 5

如何在 psql 中编写查询,以便将输出从特定名称的最大出现次数到最小次数排序?即像这样

bat  
bat  
bat  
bat  
bat  
hello  
hello  
hello  
hello  
sam  
sam  
sam  
ball  
ball  
world  
world

您可以使用临时 table 来获取所有名称的计数,然后 JOIN 到原始 table 进行排序:

SELECT yt.id, yt.name
FROM your_table yt INNER JOIN
(
    SELECT COUNT(*) AS the_count, name
    FROM your_table
    GROUP BY name
) t
ON your_table.name = t.name
ORDER BY t.the_count DESC, your_table.name DESC
SELECT count( ID ) cnt, NAME
FROM table_name
GROUP BY NAME
ORDER BY count( ID ) DESC;

使用 window 函数的替代解决方案:

select name from table_name order by count(1) over (partition by name) desc, name;

这将避免像 Tim 的解决方案那样扫描 table_name 两次,并且在 table_name 大小较大的情况下可能表现更好。

你可以用临时的table,如果原来的table是命名排序:

create temp table counted as select name, count(name) from sorting group by name;

select sorting.name from sorting, counted where sorting.name = counted.name order by count desc;