分区的MAX值超过()

时间:2012-11-23 18:25:59

标签: sql oracle plsql

我每个月都有针对特定汽车品牌的销售情况,而且每个月我都想要与销售相关的最多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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 here http://sqlfiddle.com/#!4/46770/65