3

形式の mysql テーブルがあります。それを product_revenue Product_id、年、月、収益と呼びましょう

次の列を取得する必要があります: year、month、revenue_top_5_monthly

ここで、revenue_top_5_monthly は、その月の収益が最も高かった製品の収益の合計です。上位 5 品目は月ごとに異なります。

サブクエリで1か月を選択し、収益で並べ替え、制限5を使用して値を合計することで、1か月でこれを行うことができますが、1つのクエリで毎月これを行う方法がわかりません

私が持っているのは

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 か月で 1,000 万行を超える行があるため、最終的なクエリの速度は重要です。現在、1 か月で約 80 ~ 100 秒かかります。1 時間 30 分のスロットで、16 か月ごとに約 30 のクエリを実行する必要があります。

提案されたように、私も試しました

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 に答える
-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 に答える