如何写一个SQL查询,显示同一购物车中某一特定产品的前5个销售项目?

问题描述 投票:0回答:1

我有一个表,其中有订单ID,客户ID,产品ID等列。

我想把卖出的前5个product_id与product_id 257一起排名。

我是否必须为所有产品_id 257售出的产品新建一列,然后进行排名?

或者有什么方法可以过滤数据?

请帮我指出正确的方向

sql product shopping-cart ranking
1个回答
0
投票

这个查询是。

  • 一个过滤器来获取正确的订单。
  • Aggregation。
  • 另一个过滤器,以获得前5名。

在SQL中,这看起来像。

select t.product_id, count(*)
from t
where exists (select 1
              from t t2
              where t2.order_id = t.order_id and t2.product_id = 257
             ) and
      t.product_id = 257
group by t.product_id
order by count(*) desc
fetch first 5 rows only;
© www.soinside.com 2019 - 2024. All rights reserved.