如何按国家/地区

时间:2018-01-24 21:11:12

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

下面是我们需要按月在一个国家/地区获得前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

1 个答案:

答案 0 :(得分:0)

如果您使用fetch first版本DB,则使用12c子句列出前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