简体   繁体   中英

Sql query join average of one column where another column is between two columns values of another table

I have two tables, one has two columns that have dates. The other has one column with dates and another with numeric data. I would like to join the average of the second table's numeric column values where its date column is in between the values of the two date columns in the first table. Something like the following:

Table1:

Date1        Date2 
6/28 2:00  6/30 4:00
7/1 4:00  7/4  7:00
...

Table2:

Date3    Value
6/29 1:00  6.5
6/30 3:00  2.5
7/1 5:00  3.0
7/3 9:00  5.0
...

FinalTable:

Date1        Date2   AvgValue
6/28 2:00  6/30 4:00  4.5
7/1 4:00  7/4  7:00  4.0

You can use the between operator in your join condition:

SELECT   date1, date2, AVG(value)
FROM     table1
JOIN     table2 ON date3 BETWEEN date1 AND date2
GROUP BY date1, date2
SELECT   date1, date2, AVG(value)
FROM     table1 t1
JOIN     table2 t2 ON t3.date3 >= t1.date1 AND t3.date3 < t1.date2
GROUP BY t1.date1, t1.date2

OR

SELECT   date1, date2, AVG(value)
FROM     table1 t1
JOIN     table2 t2 ON t3.date3 > t1.date1 AND t3.date3 <= t1.date2
GROUP BY t1.date1, t1.date2

Using BETWEEN is great, however it is inclusive of both sides of the range. So if you have overlapping ranges in your dual date table eg 6/28 2:00 to 6/28:4:00 AND 6/28:4:00 to 6/28 6:00 then any value landing at 4 PM would be repeated and skew your average.

You can fix this one of 2 ways.

  • Make sure your BETWEEN doesn't cause an overlap 6/28 2:00 to 6/28 3:59:59.997
  • not use BETWEEN and write out the greater than/equal to or less than to only be inclusive of 1 side of your range as in the examples above.

Note for DATETIME for sql-server is accurate to 3 milliseconds so if you put in 3:59:59.999 or .998 it will be treated the same as 4:00:00.000, the way to solve is use .997.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM