Pergunta

I have a table 'item_prices' with:

resource_id, avg_price, time_stamp, samples

Items gets a new average price inserted into the table every day. Old averages are not deleted.

How can I query the 10 items with the highest "percent increase in price" since yesterdays average? I would also like to check that the samples is > 10 to ensure accuracy.

to clarify "percent increase in price":

percent_increase = (todays_avg_price - yesterdays_avg_price) / yesterdays_avg_price

example

resource_id |  avg_price |  time_stamp |  samples

    1           450         1380526003     12
    2           650         1380526002     2
    3           980         1380526001     68

    1           400         1380440003     24
    2           700         1380440002     13
    3           400         1380440001     38

    1           900         1380300003     11
    2           250         1380300002     8
    3           300         1380300001     4

returns

resource id  |  percent_increase

     3              1.45    
     1              0.125
Foi útil?

Solução

select  
today.resource_id, 
(today.avg_price - yesterday.avg_price) / yesterday.avg_price as percent_increase
from 
item_prices today, 
item_prices yesterday
where today.resource_id = yesterday_resource_id
and   DATE(FROM_UNIXTIME(today.timestamp)) = $today
and   DATE(FROM_UNIXTIME(yesterday.timestamp)) = $yesterday
order by percent_increase desc 
limit 10

This is a self join; apologies for the archaic join syntax, it's a bad habit I find hard to shake.

Outras dicas

Please try the query below..

  select top 1 resource_id,avg_price from item_Prices 
  group by resource_id,avg_price
  having count(resource_id,avg_price)>
  10 order by time_stamp 
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top