【问题标题】:Insert rows into same table using data from different rows based on data from another table根据另一个表中的数据,使用来自不同行的数据将行插入到同一个表中
【发布时间】:2020-07-24 21:45:05
【问题描述】:

我有 2 个表: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 表中 EmployeeKey = 6023 的每个 ProjectKey 和 TaskKey(本例中为 3 行)插入到 TimecardSetDetails 表中 SetHistoryID = 10471 但使用新 EmployeeKey 的每一行的同一 TimecardDetails 表中。

我希望结果是这样的:

考勤卡详情

+--------------+-------------+------------+---------+
| 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  |
+--------------+-------------+------------+---------+

【问题讨论】:

  • 我们需要看看你的尝试。

标签: sql sql-server join sql-insert


【解决方案1】:

您可以生成带有join然后insert 的行到TimecardDetails 表中:

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      

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-10
    • 2023-03-17
    • 2019-08-30
    • 2014-09-09
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多