根据来自另一个 table 的数据,使用来自不同行的数据将行插入相同的 table

Insert rows into same table using data from different rows based on data from another table

我有 2 个 table:TimecardSetDetails、TimecardDetails

TimecardSetDetails

+--------------+-------------+--------------+
| SetDetailsID | EmployeeKey | SetHistoryID |
+--------------+-------------+--------------+
|       146358 |        6023 |        10471 |
|       146357 |        2933 |        10471 |
|       146359 |       27334 |        10471 |
+--------------+-------------+--------------+

时间卡详细信息

+--------------+-------------+------------+---------+
| SetDetailsID | EmployeeKey | ProjectKey | TaskKey |
+--------------+-------------+------------+---------+
|       146358 |        6023 | NULL       | NULL    |
|       146358 |        6023 | 22172      | 823930  |
|       146358 |        6023 | 22172      | 840709  |
|       146358 |        6023 | 22306      | 815854  |
|       146357 |        2933 | NULL       | NULL    |
|       146359 |       27334 | NULL       | NULL    |
+--------------+-------------+------------+---------+

我需要帮助将 TimecardDetails table 中 EmployeeKey = 6023 的每个 ProjectKey 和 TaskKey(在本例中为 3 行)插入相同的 TimecardDetails table TimecardSetDetails table 其中 SetHistoryID = 10471 但使用新的 EmployeeKey。

我希望结果是这样的:

时间卡详细信息

+--------------+-------------+------------+---------+
| SetDetailsID | EmployeeKey | ProjectKey | TaskKey |
+--------------+-------------+------------+---------+
|       146358 |        6023 | NULL       | NULL    |
|       146358 |        6023 | 22172      | 823930  |
|       146358 |        6023 | 22172      | 840709  |
|       146358 |        6023 | 22306      | 815854  |
|       146357 |        2933 | NULL       | NULL    |
|       146357 |        2933 | 22172      | 823930  |
|       146357 |        2933 | 22172      | 840709  |
|       146357 |        2933 | 22306      | 815854  |
|       146359 |       27334 | NULL       | NULL    |
|       146359 |       27334 | 22172      | 823930  |
|       146359 |       27334 | 22172      | 840709  |
|       146359 |       27334 | 22306      | 815854  |
+--------------+-------------+------------+---------+

您可以生成带有 join 的行,然后 insert 它们进入 TimecardDetails table:

insert into TimecardDetails (SetDetailsID, EmployeeKey, ProjectKey, TaskKey)
select s.SetDetailsID, s.EmployeeKey, d.ProjectKey, d.TaskKey
from TimecardDetails d
inner join TimecardSetDetails s on 
    s.EmployeeKey <> d.EmployeeKey
where 
    d.EmployeeKey = 6023
    and d.ProjectKey is not null
    and s.SetHistoryID = 10471