mysql - Apply value specified for date range (from, to) to value in table containing single row per date -


First of all, sorry for the title, but my english is too short to explain the meaning of my question. Suppose that we have two tables during the date table, the first table in tbl_percents contains the percentage value history if the date field is equal to to So, 0000-00-00 means that this is an incomplete range.

  Table: From date to date tbl_percents Int example content: 2001-01-01 | 2015-01-21 | 10% 2015-01-21 | 0000-00-00. 20%  

The second table is tbl_revenue , which has a revenue value for a specific date.

  Table: tbl_revenue date date revenue bigint example content: 2014-01-10 | 10 2015-01-22 | 10  

We now want to apply the percentages specified in the table in the table tbl_percents as a result, we want to get something like this:

  2014-01-10 | 1 #Bikes 2001-01-01 to 2015-01-21 percent = 10% 2015-01-22 | 2 #because 2015-01-22 to date = 20%  

Is it possible to get results in a single SQL query?

Yes you want to join one using a condition bet. I have to be careful that these types of questions are very expensive, very fast, so you do not want to do it on a huge dataset. It is being said that, you can join your tables with something similar to the following:

  SELECT b.revenue, a.percent to join an INNER as tbl_percents tbl_revenue AS b Between b.date between a.from_date and case when a.to_date = DATE ("0000-00-00") THEN DATE ("2100-01-01") ELSE a.to_date END  

Actually what I'm doing is setting something very big and in the future (such as January 1, 2100) to_date. If to_date is 0000-00-00, then I apply bigger in the future date. Otherwise, I just use to_date, by using it, I am in my table per second from the date of the revenue where the date of the revenue is between the start date of the date and the end date of my revised percentage.

Again, this is not a computationally good idea on a large dataset ... but for general purposes, it should work properly. If you are having trouble with speed / performance, then I think that using the scripting language such as r or python suggests to apply the same logic.

Good luck!


Comments

Popular posts from this blog

python - Overriding the save method in Django ModelForm -

html - CSS autoheight, but fit content to height of div -

qt - How to prevent QAudioInput from automatically boosting the master volume to 100%? -