Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 不同表中日期范围之间的平均列数_Sql - Fatal编程技术网

Sql 不同表中日期范围之间的平均列数

Sql 不同表中日期范围之间的平均列数,sql,Sql,所以我相信这里有一个简单的解决方案,但我无法让它发挥作用。我目前有两个表的结构如下: Table 1 Table 2 Name Date x y z Name Date John 03/11 91 15 3

所以我相信这里有一个简单的解决方案,但我无法让它发挥作用。我目前有两个表的结构如下:

Table 1                                                                  Table 2
Name    Date    x      y     z                                         Name      Date

John    03/11   91     15    3                                         Mary      05/26
Mary    05/25   95     10    1                                         John      08/15
John    08/14   89     13    5 
John    08/15   85     11    4
我希望能够得到每个人的x、y、z列的平均值,其中表1中的日期在表2中日期之前7天内。即约翰和玛丽的第二次和第三次参赛平均。我试过:

SELECT avg(x), avg(y), avg(z)
FROM table1
Where table1.Date
in(SELECT * FROM table2 WHERE table1.date BETWEEN table2.date AND table2.date - DATEADD(day, 7, table2.date)
GROUP BY table1.Name = table2.Name

任何帮助都将不胜感激。

我认为这应该会带来预期的结果。我假设它是SQL server,所以它将在SQL server中工作

SELECT t.name,avg(x), avg(y), avg(z)
FROM table1 t 
Where exists 
(select 1 from  table2 t2 where t2.name = t.name  and t.date between dateadd(day, -7, t2.date) and t2.date )
GROUP BY t.name 

你不想使用IN语句。您希望比较每个表中的数据,但只需要其中一个表的输出。在这种情况下,我建议使用EXISTS语句。请注意,我假设您使用的是SQL Server

-- utilizing an exists statement because the rows from tbl2 aren't needed for the output, only the comparison with tbl1 data
select      a.Name  Name
            ,avg(X) Avg_X
            ,avg(Y) Avg_Y
            ,avg(Z) Avg_Z
from        tbl1    a
where       exists(select * from tbl2 b where b.Name = a.Name and a.Dt between dateadd(day,-7,b.Dt) and b.Dt)
group by    a.Name
挑选 t1.名称,t1.日期 进入temp1 从t1连接到t2,在哪里
t1.name=t2.name和t1.date>=DateDadday,-7,t2.date和t1.date SQL对于每个数据库都是不同的-请选择一个标记,用于标识您需要解决方案的数据库5。顺便说一句,在这两者之间使用的值的顺序确实很重要。较小的/较低的/较早的值必须是第一个。例如,在99和1之间不起作用,但在1和99之间起作用。我有两个表,但您只显示一个。这有点令人困惑。