【发布时间】:2025-12-06 13:40:01
【问题描述】:
首先,如果我问了一个完全错误的问题,我想道歉 - 我是 SQL 的初学者,我不确定如何实现我的目标,但我根据我的研究假设子查询是我需要处理的。
我有两张表,一张是时间卡数据(表 1),另一张是高级项目数据(表 2)。
表 1:
+------+------------------+---------------+-------------+
| code | work_description | resource_name | total_hours |
+------+------------------+---------------+-------------+
| 101 | Time Reporting | Jane Doe | 5 |
| 101 | Time Reporting | Jane Doe | 7 |
| 101 | Time Reporting | Jane Doe | 9 |
| 201 | Time Reporting | Joe Smith | 2 |
| 201 | Time Reporting | Joe Smith | 4 |
| 201 | Time Reporting | Joe Smith | 6 |
+------+------------------+---------------+-------------+
表 2:
+------+------------+----------------+
| code | project_id | descr |
+------+------------+----------------+
| 100 | 100 | Project A |
| 101 | 100 | Time Reporting |
| 102 | 100 | Milestones |
| 103 | 100 | Planning |
| 200 | 200 | Project B |
| 201 | 200 | Time Reporting |
| 202 | 200 | Milestones |
| 203 | 200 | Planning |
+------+------------+----------------+
在表2中,当code列等于project_id列时,descr显示项目名称。除了每一行对应的项目名称之外,我还需要拉取表 1 的所有内容。
我需要什么:
+-----------+------+------------------+---------------+-------------+
| descr | code | work_description | resource_name | total_hours |
+-----------+------+------------------+---------------+-------------+
| Project A | 101 | Time Reporting | Jane Doe | 5 |
| Project A | 101 | Time Reporting | Jane Doe | 7 |
| Project A | 101 | Time Reporting | Jane Doe | 9 |
| Project B | 201 | Time Reporting | Joe Smith | 2 |
| Project B | 201 | Time Reporting | Joe Smith | 4 |
| Project B | 201 | Time Reporting | Joe Smith | 6 |
+-----------+------+------------------+---------------+-------------+
我的过程是首先我必须找到与表 1 中的每一行相关的 project_id。然后,我可以使用该值与表 2 中的 project_id 匹配,这样我就可以将项目名称从描述列
这是我目前所拥有的。这正确地提取了项目 ID(我不知道这是否是最佳实践)。我已经为项目名称尝试了几个不同的子查询,但我还不能正确地做到这一点。
SELECT
(SELECT t2.code WHERE t1.code=t2.code) as found_project_id,
t2.descr,
t1.code,
t1.work_description,
t1.resource_name,
t1.total_hours
FROM Table1 as t1
INNER JOIN Table2 as t2 ON t1.code=t2.code
所以我的问题是,除了项目名称之外,我如何使用子查询(或任何其他方法)来提取所有表 1?
【问题讨论】:
-
您可能想研究相关子查询。虽然看起来
JOIN在这里更合适,但相关子查询是另一个有用的工具。
标签: sql sql-server tsql subquery