[英]How to use two sub queries to pull values from two tables? T-SQL
首先,如果我要問一個完全錯誤的問題,我想道歉-我是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進行匹配,因此可以將項目名稱從descr列中拉出。
這是我到目前為止所擁有的。 這樣可以正確提取項目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?
您在這里不需要子查詢。 一個簡單的聯接就足夠了,因為內部聯接已經完成了您要對子查詢執行的操作:
SELECT
proj.descr,
t2.code,
t1.work_description,
t1.resource_name,
t1.total_hours
FROM table2 t2
JOIN table1 t1 ON
t1.code = t2.code
JOIN table2 proj ON
proj.code = t2.project_id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.