【问题标题】:selecting the first and last 10 rows of a sql query选择 sql 查询的前 10 行和后 10 行
【发布时间】:2021-09-16 13:42:40
【问题描述】:

你好,我有一个这样的 sqlite 数据库

price   category_id product_id
100000  89  1
2000    88  2
50000   89  3

我想为每个类别提取产品id的前5个和后5个(每个类别的最高和最低产品)

我已经写好了

SELECT *
FROM sql_data_users.products
GROUP BY product_id,category_id
ORDER BY price ASC
LIMIT 10

但它给了我 10 行而不是 10*len(category_id) 为了使解决方案完整,我想添加另一个查询并将顺序更改为 ASC,然后将 2 个查询联合起来,这可能吗?如何实现?

【问题讨论】:

    标签: sql sqlite


    【解决方案1】:

    你会使用窗口函数:

    select t.*
    from (select t.*,
                 row_number() over (partition by category order by price asc) as seqnum_asc,
                 row_number() over (partition by category order by price desc) as seqnum_desc
          from t
         ) t
    where seqnum_asc <= 5 or seqnum_desc <= 5
    order by category, price desc;
    

    【讨论】:

    • 这似乎有效,谢谢你能解释一下吗?
    • @Cenasha'bani 。 . . row_number() 枚举行——这两个调用返回每个category 升序和降序的序列号。 where 从每个中选择 5 个。
    猜你喜欢
    • 1970-01-01
    • 2019-04-25
    • 2014-02-10
    • 2011-04-21
    • 2011-01-24
    • 1970-01-01
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多