【问题标题】:Table sorting based on the number of occurrences of a particular item基于特定项目出现次数的表格排序
【发布时间】:2015-06-05 03:25:25
【问题描述】:

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

 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 

在上表中这里是出现次数

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

【问题讨论】:

    标签: sql postgresql multiple-columns


    【解决方案1】:

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

    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
    

    【讨论】:

    • 您可能需要在排序中添加, your_table.name 以增加稳定性,并为SELECT 子句中的name 列添加别名。
    • @zerkms 是的,你是对的,OP 暗示它想要这个。
    • 感谢蒂姆的回复。它第一次工作。然后我为“sam”添加另一个条目以使其计数为 4,然后执行查询。结果有点疯狂。你能在你的设置中尝试同样的方法吗?我可能做错了什么。
    • @user1416065 “疯狂”并不是最好的技术问题解释。
    • @user1416065 这听起来像是您的 Postgres 客户端的问题,与 OP 无关。你可以用“疯狂”的结果更新你的问题,但我建议不要这样做。
    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

      如果原始表命名为排序,则可以使用临时表:

      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;
      

      【讨论】:

        【解决方案4】:
        SELECT count( ID ) cnt, NAME
        FROM table_name
        GROUP BY NAME
        ORDER BY count( ID ) DESC;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-03-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-07-02
          • 2019-08-19
          • 2020-04-19
          相关资源
          最近更新 更多