select T1.C1
,T1.C2
,T2.C2
from table1 T1
join table2 T2
on T1.C1 = T2.C1
and T1.C2 != T2.C2
and T2.C1 != ''
输出:
| T1.C1 | T1.C2 | T2.C2 |
--------------------------
| 1 | A1 | B14 |
| 1 | B14 | A1 |
| 2 | A3 | B14 |
| 2 | B14 | A3 |
简单SQL查询返回两个不同项目中的所有C1。 如何从查询中删除所有重复项以获得此结果:
| T1.C1 | T1.C2 | T2.C2 |
--------------------------
| 1 | A1 | B14 |
| 2 | A3 | B14 |
答案 0 :(得分:1)
而不是:
T1.C2 != T2.C2
使用:
T1.C2 <= T2.C2
只要每个(T1.C2 < T2.C2)
对都存在等效的(T1.C2 > T2.C2)
对,就像您的示例数据一样,例如, (A1, B14)
对(B14, A1)
也存在。
否则,您可以使用:
SELECT T1.C1, T1.C2, T2.C2
FROM (
SELECT T1.C1, T1.C2, T2.C2,
ROW_NUMBER() OVER (PARTITION BY T1.C1,
IIF(T1.C2 <= T2.C2, T1.C2, T2.C2),
IIF(T1.C2 <= T2.C2, T2.C2, T1.C2)
ORDER BY T1.C2, T2.C2) AS rn
FROM table1 T1
JOIN table2 T2
ON T1.C1 = T2.C1
AND T1.C2 != T2.C2
AND T2.C1 != '') AS t
WHERE t.rn = 1
答案 1 :(得分:0)
如果我理解了你之后的内容,下面是生成此输出的代码:
T1xC2 hits
-------------------- -------------------
A1 A3,B14
A3 A1,B14
B14 A1,A3
由以下人员制作:
Declare @T1 Table (C1 int, C2 varchar(20))
Declare @T2 Table (C1 int, C2 varchar(20))
insert into @T1
Select 1, 'A1'
union select 1, 'B14'
union select 2, 'A3'
union select 2, 'B14'
Insert into @T2
Select 1, 'B14'
Union Select 1, 'A1'
union select 2, 'B14'
union select 2, 'A3'
;WITH mix
AS (
SELECT T1.C1 AS [T1xC1]
,T2.C1 AS [T2xC1]
,T1.C2 AS [T1xC2]
,T2.C2 AS [T2xC2]
,ROW_NUMBER() OVER (
ORDER BY (
SELECT NULL
)
) AS rnk
FROM @T1 T1
CROSS JOIN @t2 T2
)
,Groupwork
AS (
SELECT *
FROM mix m
WHERE EXISTS (
SELECT 1
FROM Mix m2
WHERE m.T1xC2 = m2.T1xC2
AND m.T2xC2 <> m2.T2xC2
AND m.T1xC2 <> m.t2xc2
)
)
,GroupRows
AS (
SELECT DISTINCT T1xc1, T1xC2
FROM Groupwork
)
SELECT distinct T1xC2, x.hits
FROM GroupRows g
CROSS APPLY (
SELECT STUFF((
SELECT distinct ',' + g2.T2xC2
FROM Groupwork g2
WHERE g2.T1xC2 = g.T1xC2
FOR XML PATH('')
), 1, 1, '') hits
) x