编写 Oracle 查询以获取前 5000 家商店的前 10 种产品
可能的重复:
获取每个类别的前 10 名产品
我正在寻找 Oracle 查询获取前 5000 家商店,每个商店获取前 10 个产品,每个前 10 个产品获取前 5 个子产品。所以总共我应该得到 5000*10*5 行。
有人可以帮我使用 Oracle 的分析功能得到这个吗?
我当前的查询如下所示
SELECT
store,
product,
sub-product,
count(*) as sales
FROM stores_data
GROUP BY store, product, sub-product;
请假设表名称为stores_data,其中列为store_id、product、sub_product
Possible Duplicate:
Get top 10 products for every category
I am looking for an Oracle query to get top 5000 stores and for each store get top 10 products and for each top 10 products get top 5 sub-products. So In total I should get 5000*10*5 rows.
Can someone help me get this using Oracle's analytical functions.
My current query looks like
SELECT
store,
product,
sub-product,
count(*) as sales
FROM stores_data
GROUP BY store, product, sub-product;
Please assume table names as stores_data with columns store_id , product,sub_product
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该使用dense_rank 来获取前N 行。
当然
,我现在不知道你的表,也不知道它们之间的关系。以及您想要检查的实际字段和条件,因此这只是一个简单的查询,根据 id 获取前 N 条记录。此外,此查询期望产品只有一个商店,但情况可能并非如此。至少它会向您展示如何使用
dense_rank
来获得三层排序/过滤。You should use dense_rank to get the top N rows.
Something like
Of course, I don't now your tables nor the relation between them. And the actual fields and conditions you want to check for, so this is just a simple query getting the top N records based on their id. Also, this query expects a product to have only one store which might not be the case.. At least it will show you how to use
dense_rank
to get a three-layered sorting/filtering.我将保留另一个答案,因为我认为这看起来更像是这样的表结构应该。
但是您在其他线程中描述了一个如下所示的表:
这实际上看起来像是已经聚合的数据,并且您现在想要再次分析。您的查询可能如下所示。它首先汇总销售额的总和,这样你也可以按销售额对商店和产品进行排序(表中的销售额似乎是针对子产品的。之后,你可以按销售额为商店和产品添加排名。我添加了一个我在这里也使用了排名,因此当更多记录具有相同的销售额时,编号会出现差距,这样,当您获得 8 条排名为 1 的记录时,因为它们都具有相同的销售额。第 6 条记录实际上排名为 9 而不是 2,因此您将只选择 8 家顶级商店(您想要 5 家,但为什么要跳过其他 3 家,如果它们实际上销售完全相同)而不是其他 4 家。
I'll leave the other answer because that looks more like how such a table structure should be, I think.
But you described in your other thread to have a table that looks like this:
That actually looks like data that is aggregated already and that you do now want to analyze again. You query could look like this. It first aggregates the sum of the sales, so you can order shops and products by sales too (the sales in the table seem to be for the subproducts. After that, you can add ranks to the shops and products by sales. I added a rank to the subproducts too. I used rank here, so there is a gap in the numbering when more records have the same sales. This way, when you got 8 records with a rank of 1, because they all have the same sales, the 6th record will actually have rank 9 instead of 2, so you will only select the 8 top stores (you wanted 5, but why skip the other 3 if they actually sold exactly the same) and not 4 others too.