3

我有一个格式的mysql表,我们称之为product_revenue Product_id,year,month,revenue

我需要得到以下列:年,月,收入_top_5_monthly

其中income_top_5_monthly 是当月收入最高的产品的收入总和。排名前 5 位的产品因月而异。

我可以通过使用子查询选择一个月,按收入排序并使用限制 5,然后对值求和,然后在单个查询中为每个月执行此操作,我可以在一个月内执行此操作

我所拥有的是

select 'y' as year, 'x' as month, sum(revenue) as revenue_top_5 from
(select revenue from product_revenue
where month=x and year=y
order by revenue desc
limit 5) as top5

但我每个月都需要它一次。

product_revenue 表在 16 个月内有超过 1000 万行,因此最终查询速度具有很大的相关性。目前一个月大约需要 80-100 秒,我必须在 1 小时 30 分钟的时间段内运行大约 30 个这样的查询,每个查询需要整个 16 个月。

按照建议,我也尝试过

select * from
(
select dd.year, dd.monthnumber,
u.product_id, sum(revenue) as revenue
from source
group by 1,2,3
)a
where 
(select count(*) from
                            (select dd.year, dd.monthnumber,
                            u.product_id, sum(revenue) as revenue
                            from source
                            group by 1,2,3)b
where b.year=a.year and b.monthnumber=a.monthnumber and b.revenue<=a.revenue
)<=5

但不返回任何行。单独的子查询 a 和 b 按命名返回预期的行。

4

3 回答 3

2

试试这个查询

select * from
(select 
@rn:=if(@prv=product_id, @rn+1, 1) as rId,
@prv:=product_id as product_id,
year, 
month,
revenue
from tbl
join
(select @prv:=0, @rn:=0)tmp
order by 
product_id, revenue desc) a
where rid<=5

SQL 小提琴

| RID | PRODUCT_ID | YEAR | MONTH | REVENUE |
---------------------------------------------
|   1 |          1 | 2013 |     1 |     100 |
|   2 |          1 | 2013 |     1 |      90 |
|   3 |          1 | 2013 |     1 |      70 |
|   4 |          1 | 2013 |     1 |      60 |
|   5 |          1 | 2013 |     1 |      50 |
|   1 |          2 | 2013 |     1 |    5550 |
|   2 |          2 | 2013 |     1 |     550 |
|   3 |          2 | 2013 |     1 |     520 |
|   4 |          2 | 2013 |     1 |     510 |
|   5 |          2 | 2013 |     1 |     150 |
于 2013-05-15T09:19:22.300 回答
0

也许:

   SELECT t1.year,
          t1.month,
          (SELECT SUM(t2.revenue) 
           FROM product_revenue t2
           WHERE t2.month = t1.month
           AND t2.year = t1.year
           ORDER BY t2.revenue DESC LIMIT 5 ) AS revenue_top_5
   FROM product_revenue t1
   GROUP BY  t1.year, t1.month
于 2013-05-15T09:30:21.103 回答
-2

试试这个和c。

select top 5 'y' as year,'x' as month,sum(total) as top_5 From
(select sum(revenue) as total from product_revenue
where month=x and year=y
order by revenue desc) as t
于 2013-05-15T09:13:40.430 回答