简体   繁体   English

如何根据时间范围联接将字段从一个表更新到另一个表?

[英]How to update field from one table to another based on a time range join?

I have tried many different things but I am really struggling with this issue. 我已经尝试了许多不同的方法,但是我确实为这个问题而苦苦挣扎。 I am used to MySQL, SQLite, and other databases but I can't seem to figure this one out in Access. 我已经习惯了MySQL,SQLite和其他数据库,但是我似乎无法在Access中弄清楚这一点。

I have two tables that I want to join based on if the timestamps of table1 fall within a range of timestamps in table2 grouped by ID. 我有两个要联接的表,如果table1的时间戳落在table2的时间戳范围内(按ID分组)。 See the following: 请参阅以下内容:

Table1: 表格1:

ID  Timestamp
    8:00 AM
    8:01 AM
    8:02 AM
    8:03 AM
    8:04 AM
    8:05 AM
    8:06 AM
    8:07 AM
    8:08 AM
    8:09 AM
    8:10 AM
    8:11 AM
    8:12 AM
    8:13 AM
    8:14 AM
    8:15 AM
    8:16 AM
    8:17 AM
    8:18 AM
    8:19 AM

Table2: 表2:

ID  Timestamp
1   8:00 AM
1   8:02 AM
1   8:04 AM
1   8:06 AM
2   8:10 AM
2   8:12 AM
2   8:14 AM
2   8:16 AM

What I want to happen in Table1: 我想在表1中发生什么:

ID  Timestamp
1   8:00 AM
1   8:01 AM
1   8:02 AM
1   8:03 AM
1   8:04 AM
1   8:05 AM
1   8:06 AM
    8:07 AM
    8:08 AM
    8:09 AM
2   8:10 AM
2   8:11 AM
2   8:12 AM
2   8:13 AM
2   8:14 AM
2   8:15 AM
    8:16 AM
    8:17 AM
    8:18 AM
    8:19 AM

Here is what I tried initially (and wish would work) but have gone through many iterations of different queries without getting anywhere. 这是我最初尝试的方法(希望可以使用),但是经历了许多不同查询的多次迭代,却一无所获。

UPDATE Table1 
  SET Table1.ID = Table2.ID 
  WHERE Table1.Timestamp IN (SELECT Table2.Timestamp GROUP BY Table2.ID);

I either get no output (Table1.ID remains empty) or I get the error "Operation must use an updatable query". 我要么没有输出(Table1.ID保持为空),要么得到错误“操作必须使用可更新的查询”。

You need to create a temp table and use it as a temporary recordset to use to search the records. 您需要创建一个临时表,并将其用作临时记录集以用于搜索记录。 The reason for this is that you need the Min/Max timestamp per ID, which requires an aggregate query, which cannot be used in an update query. 这样做的原因是,您需要每个ID的最小/最大时间戳,这需要一个聚合查询,而该查询不能在更新查询中使用。

SELECT Table2.ID, 
Min(Table2.TS) AS MinOfTS, 
Max(Table2.TS) AS MaxOfTS
 INTO try      '<- this is your temporary table.
FROM Table2
GROUP BY Table2.ID;

Now that we have values we can use to search with in our temp table, we can just reference that in our UPDATE statement. 现在我们有了可以在临时表中进行搜索的值,我们可以在UPDATE语句中引用它。

UPDATE Table1, try SET Table1.ID = [try].[ID]
WHERE (((Table1.TS) Between [try].[minofts] And [try].[maxofts]));

Edit: I suppose you could use a DLookup - but they tend to run extremely slow compared to this method. 编辑:我想您可以使用DLookup但与这种方法相比,它们的运行速度非常慢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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