【问题标题】:how to get the top 3 product sale in a month by country [duplicate]如何按国家/地区获得一个月内排名前三的产品销售额[重复]
【发布时间】:2018-07-04 00:57:39
【问题描述】:

下面是我们需要从中获得按月在一个国家/地区销售前 3 名产品的数据库:

USA Lenevo  1/1/2017
USA Toshiba 1/1/2017
USA Dell    1/2/2017
USA Asus    1/2/2017
USA Lenevo  1/1/2017
USA Toshiba 1/1/2017
USA Dell    1/2/2017
USA Lenevo  1/1/2017
USA Toshiba 1/1/2017
USA Dell    1/2/2017

Bangladesh  Lenevo  1/1/2017
Bangladesh  Toshiba 1/1/2017
Bangladesh  Dell    1/2/2017
Bangladesh  Lenevo  1/1/2017
Bangladesh  Toshiba 1/1/2017
Bangladesh  Dell    1/2/2017
Bangladesh  Asus    1/2/2017

India   Lenevo  1/1/2017
India   Toshiba 1/1/2017
India   Dell    1/2/2017
India   Lenevo  1/1/2017
India   Toshiba 1/1/2017
India   Dell    1/2/2017        
India   Asus    1/2/2017

Thailand    Lenevo  1/1/2017
Thailand    Toshiba 1/1/2017
Thailand    Dell    1/2/2017
India           Asus    1/2/2017
Thailand    Lenevo  1/1/2017
Thailand    Toshiba 1/1/2017
Thailand    Dell    1/2/2017
Thailand    Lenevo  1/1/2017
Thailand    Toshiba 1/1/2017

USA Lenevo  2/1/2017
USA Toshiba 2/1/2017
USA Dell    2/2/2017
USA Lenevo  2/5/2017
USA Toshiba 2/6/2017
USA Dell    2/9/2017
USA Lenevo  2/5/2017

Bangladesh  Lenevo  2/1/2017
Bangladesh  Toshiba 2/1/2017
Bangladesh  Dell    2/2/2017
Bangladesh  Lenevo  2/1/2017
Bangladesh  Toshiba 2/1/2017
Bangladesh  Dell    2/2/2017
Bangladesh  Lenevo  2/3/2017

India   Lenevo  2/1/2017
India   Toshiba 2/1/2017
India   Dell    2/2/2017
India   Asus    2/2/2017


Thailand    Lenevo  2/1/2017
Thailand    Toshiba 2/1/2017
Thailand    Dell    2/2/2017
Thailand    Asus    2/2/2017
Thailand    Lenevo  2/1/2017
Thailand    Toshiba 2/1/2017
Thailand    Dell    2/2/2017
Thailand    Lenevo  2/1/2017
Thailand    Toshiba 2/1/2017

【问题讨论】:

  • 您有问题吗?注意:哪个版本的 Oracle?
  • (1) 可以发布家庭作业问题,但您必须展示您尝试过的内容以及遇到困难的地方。 (2) 关于日期,当你写1/2/2017 之类的东西而没有解释时,你是在让我们猜测是 1 月 2 日还是 2 月 1 日。我们不能——我们不是读心术的人。 (3) 当您谈到“前 3 名”时,可能会出现平局(第一名:六次销售,第二名:五次销售,第三名:两种不同的产品,每个销售四次)。在这种情况下,您必须指定所需的结果。例如:如果有并列,则显示所有并列第三的产品。

标签: sql oracle greatest-n-per-group


【解决方案1】:

如果您使用DB 版本12c,使用fetch first 子句列出前N 个查询非常容易。最后按照monthcountrybrand的顺序对列进行分组,并应用分组功能。

这里的重要技巧是考虑最小值有序列的多重存在概率的情况。即您限制为 3 个,但第 5 列的第 4 列的品牌数相等。在这种情况下,请考虑使用 with ties 子句来包含所有最小相等事件:

select to_char(sale_date,'yyyymm') "monthOfYear", country, brand, count(1) cnt
  from sales
 group by to_char(sale_date,'yyyymm'), country, brand
 order by count(1) desc
 fetch first 3 rows with ties;

假设您有一个包含这些列的 sales 表:

SQL> desc sales
     COUNTRY   VARCHAR2(35)
     BRAND     VARCHAR2(35)
     SALE_DATE DATE

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-06
    • 1970-01-01
    • 2020-07-13
    • 2019-12-07
    • 1970-01-01
    相关资源
    最近更新 更多