2016-03-17 53 views
1

我試圖按照標題爲SQL Server創建select語句。 我的數據是:顯示基於加入ID的兩個不同colums中的值

ID | JoiningID | Value | 

1 | 1 | 10 

2 | 1 | 11 

3 | 2 | 10 

4 | 2 | 10 

5 | 3 | 15 

6 | 3 | 9 

我試圖輸出三列這將是這樣的:

JoiningID | Column1值| Column2值

1 | 10 | 11 

2 | 10 | 10 

3 | 15 | 9 

條件是它需要在select語句內而不是在where語句中。

謝謝你的時間。

+3

如果joinid的值超過2,該怎麼辦? –

+0

@vkp道歉,永遠不會超過2個值。 – Revokez

+0

什麼決定哪些值應該在Column1值中,哪些值應該在Column2值中? –

回答

0

您可以枚舉值,然後使用pivot或有條件聚集:

select joiningid, 
     max(case when seqnum = 1 then value end) as value1, 
     max(case when seqnum = 2 then value end) as value2 
from (select t.*, row_number() over (partition by joiningid order by id) as seqnum 
     from t 
    ) t 
group by joiningid; 
0

你可以簡單地做..

SELECT * FROM TABLE1 
WHERE JoiningID IN(SELECT JoiningID from TABLE2) 

或..

SELECT * FROM TABLE1 
WHERE JoiningID NOT IN(SELECT JoiningID from TABLE2) 

或者,你可以做JOIN或LEFT JOIN ..