Note that there are some explanatory texts on larger screens.

plurals
  1. POsql select top 5 every month
    primarykey
    data
    text
    <p>I have a mysql table of the format, let's call it product_revenue Product_id, year, month, revenue</p> <p>and i need to get the following columns: year, month, revenue_top_5_monthly</p> <p>where revenue_top_5_monthly is the sum of revenue of the products that had the highest revenue in that month. The top 5 products vary from month to month.</p> <p>I can do this for a single month by selecting with a sub-query a single month, sorting by revenue and using limit 5, then summing up the value, but I wouldn't know how to do this for every month in a single query</p> <p>What I have is</p> <pre><code>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 </code></pre> <p>but I need it for every month in one shot.</p> <p>The product_revenue table has over 10m rows for 16 months, so final query speed is of large relevance. For one month it currently takes about 80-100 sec, and I have to run about 30 such queries, each for the whole 16 months, in a 1h 30min slot.</p> <p>as suggested, I also tried</p> <pre><code>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&lt;=a.revenue )&lt;=5 </code></pre> <p>but returns no rows. The individual subqueries a and b return the expected rows as named.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload