2017-02-15 134 views
0

首先,我想道歉,如果我問完全錯誤的問題 - 我是一個初學者,當談到SQL,我不知道如何實現我的目標,但我假設根據我的研究子查詢是我需要合作的。我有兩張表,一張帶時間卡數據(表1),另一張帶高層次項目數據(表2)。如何使用兩個子查詢從兩個表中提取值? T-SQL

表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中,當代碼列等於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,我可以使用該值來匹配表PROJECT_ID 2,所以我可以將項目名稱從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的除了項目名稱?

+0

您可能想要研究_correlated subquery_。雖然看起來'JOIN'在這裏更合適,相關的子查詢是另一個有用的工具。 – HABO

回答

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

此查詢從t2.descr中取得值,其中t1.code = t2.code(又名錶2中的「時間報告」),但我正在查找也位於descr列中的項目名稱,但僅在發生t2.code = t2.project_id。 – user7571220

+0

@ user7571220我編輯了我的答案以更正此錯誤 – pquest

+0

此功能完美無缺。非常感謝你的幫助! – user7571220