Jump to content

[SOLVED] Time consuming query


Anfaenger

Recommended Posts

Hi all,

 

I have a table with id's, dates and numeric values. I am trying to calculate an average for different calendar years using only the latest date entry for each unique id. Here is the query that works and returns the correct result:

select avg(value)from table p
where p.date=(select max(b.date) from table b where year(date)='2008/2007/2006/etc' and p.id=b.id)

 

The problem is, that this query takes very long before returning a result (nearly 2 minutes). There are close to 400,000 entries in that table and round about 5,000 of them will be used for calculating the average for each year.

 

My question is, does anyone have a more elegant and faster solution to achieve the same results or can I optimize the query somehow for faster results? Would it be advisable to put some information  in a new table for better performance?

 

Thank you very much

Link to comment
Share on other sites

You would probably be better off storing YEAR(date) already calculated (breaks some ideas of normalization but helps with performance ;p).  Also, hopefully everything is indexed well.

 

 

 

Some other changes might be possible, but like Phoenix~Fire said, it's just a beast of a query.

Link to comment
Share on other sites

Thank you for your reply.

 

I am already storing calculated years so that only the last year needs to be calculated over and over. However, sometimes data for previous years will be added and the whole query needs to be proccessed. I think I will have to come up with another way to store the data so that it is faster.

 

Thanks for your input.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.