SQL SELECT DISTINCT CONCAT(ColumnA,' |',ColumnB)

时间:2017-11-15 13:27:10

标签: sql distinct concat

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

表A

ColumnA
1                
1                
2
3
4
4
5

表B

ColumnX
a
a
b
c
d
d
e

我想连接这两个列,所以它们看起来像下面的结果没有dublicates

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

所以我试图做以下事情:

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

但是我还在争吵!?为什么????

2 个答案:

答案 0 :(得分:0)

你可以通过row_numbers()函数&生成row_numbers。然后concat他们(SQL Server)

;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

答案 1 :(得分:0)

仅在没有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