0

特定の自動車ブランドの月間売上があり、毎月、売上に関連して最大 5 つの自動車ブランドが必要です。次に、これらの最大ブランドのそれぞれの横に、この特定のブランドが過去 4 か月間に上位 5 位以内に入った回数 (存在する場合) を示します。

たとえば、テーブル データが次の場合:

Timestamp | Brand | Sales
1/1/2012  | A     | 23
1/1/2012  | B     | 45
1/1/2012  | C     | 11
1/1/2012  | D     | 3
1/1/2012  | E     | 55
1/1/2012  | F     | 1
1/1/2012  | G     | 22
---------------------------
1/2/2012  | A     | 93
1/2/2012  | B     | 35
1/2/2012  | C     | 01
1/2/2012  | D     | 100
1/2/2012  | E     | 45
1/2/2012  | F     | 77
1/2/2012  | G     | 12

2 か月のデータの場合、2 月のクエリ出力 (2 月と 1 月のみを調べる) は次のようになります。

Max_ Brand_Sales| Reappearance_Factor
--------------------------------------
E               | 1
B               | 1
D               | 0
F               | 0
A               | 1
4

2 に答える 2

2
Select
  c.Brand,
  nvl(Count(p.Brand), 0) As Reappearance_Factor
From (
  Select
    Brand,
    Rank () Over (Order By Sales Desc) as r
  From
    Sales
  Where
    Timestamp = Date '2012-02-01'
  ) c
    left outer join (
  Select
    Brand,
    Rank () Over (Partition By Timestamp Order By Sales Desc) as r
  From
    Sales
  Where
    Timestamp >= Date '2011-10-01' And
    Timestamp < Date '2012-02-01'
  ) p
  on c.Brand = p.Brand And p.r <= 5
Where
  c.r <= 5
Group By
  c.Brand

http://sqlfiddle.com/#!4/46770/21

于 2012-11-23T20:24:51.723 に答える