比较两个不同列中相同字段的值
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了比较两个不同列中相同字段的值相关的知识,希望对你有一定的参考价值。
我需要将一列中的两个部分并排放在一个表中,具有相同的描述和不同的“外部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
答案
如果我理解正确,您可以使用完整的外部联接:
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;
另一答案
你需要dense_rank()
并做条件聚合:
select max(case when OUTERID = 1 then DESCRIPTION end) as DESCRIPTION_1,
max(case when OUTERID = 2 then DESCRIPTION end) as DESCRIPTION_2
from (select t.*,
dense_rank() over (order by DESCRIPTION) as seq
from table t
) t
group by seq;
另一答案
使用cte :(虽然,我不知道为什么你需要提供两个列而不是仅仅识别'dupes')
表:
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
以上是关于比较两个不同列中相同字段的值的主要内容,如果未能解决你的问题,请参考以下文章