[英]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: 表格1:
Date1 Date2
6/28 2:00 6/30 4:00
7/1 4:00 7/4 7:00
...
Table2: 表2:
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: 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: 您可以在联接条件中使用
between
运算符:
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. 使用
BETWEEN
很棒,但是它涵盖了范围的两侧。 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. 因此,如果双重日期表中的范围重叠,例如
6/28 2:00 to 6/28:4:00 AND 6/28:4:00 to 6/28 6:00
则6/28 2:00 to 6/28:4:00 AND 6/28:4:00 to 6/28 6:00
4点的任何价值重复并倾斜您的平均值。
You can fix this one of 2 ways. 您可以通过2种方法之一来解决此问题。
BETWEEN
doesn't cause an overlap 6/28 2:00 to 6/28 3:59:59.997
BETWEEN
不会造成重叠6/28 2:00 to 6/28 3:59:59.997
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. BETWEEN
并写出大于/等于或小于等于范围的1个边,如上面的示例所示。 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. 注意sql-server的
DATETIME
精确到3毫秒,因此,如果您输入3:59:59.999或.998,则将其与4:00:00.000相同,解决方法是使用.997。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.