0

我每月都有特定汽车品牌的销售额,并且每个月我都想要与销售额相关的最多 5 个汽车品牌。然后,在这些最大品牌旁边,我想要一个数字(如果有),表明这个特定品牌在前 4 个月中进入前五名的次数。

例如,如果表数据是:

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 月和 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 回答
0

试试这个:

1) 计算每个品牌每月排名的查询:

SELECT
  s.Brand,
  trunc(s.Timestamp,'MONTH') month_start,
  rank() OVER (PARTITION BY trunc(s.Timestamp,'MONTH') 
               ORDER BY s.Sales DESC) as monthly_rank
FROM Sales s;

2)查询输出当月排名前5的品牌:

SELECT
 t.Brand
FROM
(
  SELECT
    s.Brand,
    trunc(s.Timestamp,'MONTH') month_start,
    rank() OVER (PARTITION BY trunc(s.Timestamp,'MONTH') 
                 ORDER BY s.Sales DESC) as monthly_rank
  FROM Sales s
) t
WHERE monthly_rank <= 5
  AND month_start = trunc(sysdate,'MONTH');

3)查询计算过去4个月的“再现”

SELECT
 t.Brand,
 count(*) as top
FROM
(
  SELECT
    s.Brand,
    trunc(s.Timestamp,'MONTH') month_start,
    rank() OVER (PARTITION BY trunc(s.Timestamp,'MONTH') 
                 ORDER BY s.Sales DESC) as monthly_rank
  FROM Sales s
) t
WHERE monthly_rank <= 5
  AND t.month_start BETWEEN add_months(sysdate, -1)
                        AND add_months(sysdate, -5)
GROUP BY t.Brand;

4) 最后一件事 -LEFT JOIN查询 2 和 3

SQLFiddle在这里http://sqlfiddle.com/#!4/46770/65

于 2012-11-23T23:38:29.943 回答