根据加入ID显示两个不同列中的值

时间:2016-03-17 15:11:24

标签: sql sql-server

我正在尝试根据标题为SQL Server创建一个select语句。 我的数据是:

ID | JoiningID | Value | 

1 | 1 |  10

2 | 1 | 11

3 | 2 | 10

4 | 2 | 10

5 | 3 | 15

6 | 3 | 9

我正在尝试输出三列,如下所示:

加入ID | Column1值| Column2值

1 | 10 | 11

2 | 10 | 10

3 | 15 | 9

这是因为它需要在select语句中而不是在where语句中。

感谢您的时间。

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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 ..