我需要在一个表中并列放置两列,它们具有相同的描述和不同的“外部ID”。输入表如下所示:
+--+-------+-----------+
|ID|OUTERID|DESCRIPTION|
+--+-------+-----------+
|1 |1 |some desc 1|
+--+-------+-----------+
|2 |1 |some desc 2|
+--+-------+-----------+
|3 |1 |some desc 3|
+--+-------+-----------+
|4 |2 |some desc 2|
+--+-------+-----------+
|5 |2 |some desc 3|
+--+-------+-----------+
这是我要从选择中实现的目标:
+-------------+-------------+
|DESCRIPTION_1|DESCRIPTION_2|
+-------------+-------------+
|some desc 1 |NULL |
+-------------+-------------+
|some desc 2 |some desc 2 |
+-------------+-------------+
|some desc 3 |some desc 3 |
+-------------+-------------+
我尝试了一个简单的JOIN,但是如您所见,我也需要显示不匹配的值。
SELECT a.DESCRIPTION AS DESCRIPTION_1,
b.DESCRIPTION AS DESCRIPTION_2
FROM My_Table a
JOIN My_Table b on a.DESCRIPTION = b.DESCRIPTION
WHERE a.OUTERID = 1
AND b.OUTERID = 2
答案 0 :(得分:4)
您需要assign()
并进行条件聚合:
None
答案 1 :(得分:3)
如果我理解正确,则可以使用完全外部联接来完成此操作:
SELECT a.DESCRIPTION AS DESCRIPTION_1,
b.DESCRIPTION AS DESCRIPTION_2
FROM (SELECT a.*
FROM My_Table a
WHERE a.OUTERID = 1
) a FULL JOIN
(SELECT b.*
FROM My_Table b
WHERE b.OUTERID = 2
) b
ON a.DESCRIPTION = b.DESCRIPTION;
答案 2 :(得分:0)
使用cte :(不过,我不确定为什么您需要同时显示两列而不是仅标识“重复项”)
表格:
Create Table #tbl
(
ID Int,
OUTERID Int,
DESCRIPTION VarChar(20)
)
Insert Into #tbl Values
(1,1,'some desc 1'),
(2,1,'some desc 2'),
(3,1,'some desc 3'),
(4,2,'some desc 2'),
(5,2,'some desc 3')
CTE
With cte As
(
Select Description, Count(Distinct OuterID) As recs From #tbl
Group By Description
)
Select
Case When recs = 2 Or recs = 1 Then Description End As Description_1,
Case When recs = 2 Then Description End As Description_2
From cte