So I have 2 tables I need to join. Table1 includes a column called JDAY which hold the values 1.5, 2.5, 3.5…365.5. It looks like:
JDAY
1.5
2.5
3.5
4.5
5.5
etc.
I would like to join it with Table2, which looks like:
JDAY WSC
1 1
5 .9
8 .7
366 .5
The final result should have a JDAY column with all the values from Table1, and the WSC value from Table2 corresponding to the closest JDAY value less than or equal to that in Table2. For example, JDAY=5.5 in Table1 corresponds to WSC=.9, because 5.5 is between 5 and 8. It would look like this:
JDAY WSC
1.5 1
2.5 1
3.5 1
4.5 1
5.5 .9
6.5 .9
7.5 .9
8.5 .7
9.5 .7
etc.
One way to get the result is to use a correlated subquery:
UPDATED
You noted you wanted
the largest value of WSCless than JDAY; I’m taking that to mean that you want themaximum value of WSCfrom the rows in Table2 that have a JDAY value LESS THAN the JDAY value from the Table1 row. That seems to fit with the result set you are showing. (If I got that wrong (which I may have), it was my misunderstanding, reading something you didn’t intend, if so, please feel free to correct me.)UPDATE
I have a better understanding, you want the value of WSC from the row in Table2 that has the largest JDAY value that is earlier than the JDAY value in Table1. You want the WSC from the row with with the latest earlier date. The queries in my answer are modified to satisfy this requirement.
Another alternative to get basically the same result set is to use a theta-join (that is, a join on an inequality predicate)
UPDATED
That will work as long as there aren’t any “duplicate” values of JDAY in Table2. If there are duplicate values, you’ll need to have a way to eliminate any duplicates that get returned. Adding a
GROUP BY t.JDAYwould be sufficient, but not deterministic. (That is, you wouldn’t be guaranteed which row you were getting the WSC value from.)Here, we are asking for every row from Table1, AND any “matching” rows from Table2, matching on the JDAY from Table2 being LESS THAN the JDAY from Table1. For each row in Table1, we will rummage through all the “matching” rows from Table2 (if any) and we will pick out the largest
WSC valuematching JDAY from Table2 and return it in the subquery (inline view) aliased as t. We can then join that result set back to Table2, to get the matching row, along with the WSC value on that row.One difference between these queries comes into play when there are “duplicate” values of JDAY in Table1, they will return slightly different result sets. The first query will return all the rows from Table1, including duplicate values of JDAY. The second query will remove duplicate values of JDAY from Table 1, and return a distinct set of values for JDAY.
UPDATE:
I’ve updated the answer above, not getting the
MAX(WSC)value, but instead getting the WSC value from the row in Table2 with the closest JDAY that is less than the Table1 JDAY.