【问题标题】:SQL SELECT DISTINCT CONCAT(ColumnA,'|',ColumnB)SQL SELECT DISTINCT CONCAT(ColumnA,'|',ColumnB)
【发布时间】:2018-04-28 18:01:02
【问题描述】:

所以我有两个表,我想在每个表中的一个列上使用连接。

表A

ColumnA
1                
1                
2
3
4
4
5

表B

ColumnX
a
a
b
c
d
d
e

我想连接这两列,这样它们最终看起来像下面的结果,没有重复

Result
1|a
2|b
3|c
4|d
5|e

所以我尝试了以下操作:

SELECT DISTINCT CONCAT(ColumnA,'|',ColumnB) where tableA.Relation = TableB.Relation

但我仍然得到重复!?为什么????

【问题讨论】:

  • 你加入的是什么关系?
  • 只是一个包含 ID 的列
  • 你确定有重复的..?确保您只选择一列(即concat())而不是像select distinct concat(....) ,some_column from ...

标签: sql distinct concat


【解决方案1】:

您可以通过row_numbers() 函数然后concat 它们(SQL Server)生成row_numbers

;with cte as
(
    SELECT *, ROW_NUMBER() over (order by (select 1)) rn FROM <table>
),cte1 as
(
   SELECT *, ROW_NUMBER() over (order by (select 1)) rn FROM <table>
)

select DISTINCT CONCAT(c.ColumnA, '|',c1.ColumnX) from cte c
join cte1 c1 on c1.rn = c.rn

【讨论】:

  • OP 在他的谓词tableA.Relation = TableB.Relation中有一些东西
  • 为什么是“Row_Number()”?我拥有的值与行号无关,真正的最终结果将如下所示:* 812436562|2016321045 812436562|2016328124 812436562|2016349124 但我只是想连接到来自不同表的列并确保没有重复最终结果。
  • @ShamatixShamatix 根据您提供的数据或您不想使用row_number(),上述内容是正确的,然后编辑问题添加更多示例数据和结果
【解决方案2】:

这在没有 CTE 的情况下是相似的

select distinct A.a + '|' + B.b
from
(select a, Row_Number() over (order by a) as rowNum
from TableA) as A, 
(select b, Row_Number() over (order by b) as rowNum
from TableB) as B 
where A.rowNum = b.rowNum

【讨论】:

  • 为什么是“Row_Number()”?我拥有的值与行号无关,真正的最终结果将如下所示:* 812436562|2016321045 812436562|2016328124 812436562|2016349124 但我只是想连接到来自不同表的列并确保没有重复最终结果。
猜你喜欢
  • 2022-11-01
  • 2018-03-15
  • 1970-01-01
  • 2012-02-20
  • 1970-01-01
  • 1970-01-01
  • 2013-12-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多