You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按item_id出现频次排序数据集并返回所有行?

Got it, let's figure out how to sort your entire dataset by how often each item_id shows up, while keeping every single row in the results. I'll break down the solutions for common databases below:

解决方案

1. MySQL/MariaDB

You can use a subquery to first calculate the occurrence count for each item_id, then join that back to your original table, and sort by the count:

SELECT t.*
FROM your_table t
JOIN (
    SELECT item_id, COUNT(*) AS occurrence_count
    FROM your_table
    GROUP BY item_id
) cnt ON t.item_id = cnt.item_id
ORDER BY cnt.occurrence_count DESC, t.id ASC;

The ORDER BY cnt.occurrence_count DESC sorts rows by how frequent their item_id is (most common first). Adding t.id ASC ensures rows with the same item_id stay in their original table order—feel free to swap this with another column if you prefer a different secondary sort.

2. PostgreSQL & SQL Server

These databases support window functions, which let you calculate the occurrence count directly in the ORDER BY clause without needing a separate subquery join:

SELECT *
FROM your_table
ORDER BY COUNT(*) OVER (PARTITION BY item_id) DESC, id ASC;

The COUNT() OVER (PARTITION BY item_id) window function computes the total number of times each item_id appears, and we use that value to sort the entire dataset.

Quick Notes

  • Replace your_table with your actual table name
  • Swap DESC with ASC if you want to sort from least frequent to most
  • The secondary sort (like id ASC) is optional but helps keep results consistent when multiple item_ids have the same frequency

For example, using your sample data, the sorted result would look like this:

iditem_idcolumn2column3column4
112HiDataHereMoreData
212HiDataHereMoreData
512HiDataHereMoreData
314HiDataHereMoreData
413HiDataHereMoreData
621HiDataHereMoreData

内容的提问来源于stack exchange,提问作者Curtis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:51:13