在组内排序

Sorting within a group

我有 2 个表:ItemsCategories。每个项目都属于一个类别。

Table 项

║ Item_name ║ Category_id ║ Price ║

║ A         ║ Cat_1    ║ 100   ║

║ B         ║ Cat_1    ║ 50    ║

║ C         ║ Cat_2    ║ 98    ║

║ D         ║ Cat_2    ║ 99    ║

║ E         ║ Cat_1    ║ 40    ║

Table 类别

║ Category_id ║ Category_name ║

║ Cat_1       ║ X             ║

║ Cat_2       ║ Y             ║

我想按价格对一个类别中的所有项目进行排序。我怎样才能做到这一点?预期结果:

║ Item_name ║ Category ║ Price ║

║ E         ║ Cat_1    ║ 40    ║

║ B         ║ Cat_1    ║ 50    ║

║ A         ║ Cat_1    ║ 100   ║

║ C         ║ Cat_2    ║ 98    ║

║ D         ║ Cat_2    ║ 99    ║

根据您的预期结果,您甚至不需要类别 table。只需按所需顺序从项目 table 中 select。

SELECT i.Item_Name, i.Category_ID, i.Price
    FROM items i
    ORDER BY i.Category_ID, i.price;

但是如果您想包含类别名称,一个简单的连接就可以了。

SELECT i.Item_Name, i.Category_ID, c.Category_Name, i.Price
    FROM items i
        INNER JOIN categories c
            ON i.Category_ID = c.Category_ID
    ORDER BY i.Category_ID, i.price;

编辑 根据评论中的问题,如何 return SQL 服务器每个类别中最便宜的 50 件商品。您可以使用常见的 table 表达式 (CTE) 并利用 ROW_NUMBER 函数按价格对每个类别中的项目进行编号。

WITH cteOrderByCategory AS (
    SELECT i.item_name, i.Category_ID, i.price,
           ROW_NUMBER() OVER(PARTITION BY i.Category_ID ORDER BY i.price) AS RowNum
        FROM items i
)
SELECT obc.item_name, obc.Category_ID, obc.price
    FROM cteOrderByCategory obc
    WHERE obc.RowNum <= 50
    ORDER BY obc.Category_ID, obc.price;

无需组团,只需下单:

select
    i.Item_Name,
    c.Category_name,
    i.Price
from items i
    inner join Categories c on i.category_id = c.category_id
order by c.category_id, i.price