SQL显示不重复LEFT JOIN行

时间:2014-01-14 20:46:29

标签: sql sql-server sql-server-2008 duplicates left-join

我想要做的是相互匹配行,并排除所有匹配多次的行。

SQLFiddle

数据集(请记住,这是简化的,我需要从查询中检索更多信息)

表1:

NAME    PART1       PART2

ABC     FirstABC    SecondABC
BAC     FirstBAC    SecondBAC
BAC     SecondBAC   FirstBAC
CBA     FirstCBA    SecondCBA
DAE     FirstDAE    SecondDAE
EDA     FirstEDA    SecondEDA

表2:

ITEM1       ITEM2

FirstABC    SecondABC
FirstBAC    SecondBAC
FirstBAC    SecondBAC
FirstCBA    SecondCBA
FirstDAE    SecondDAE
FirstEDA    SecondEDA

到目前为止我所拥有的:

SELECT *
FROM TOMATCH as T
LEFT JOIN AGAINST as A
ON (
  T.Part1 = A.Item1
  OR T.Part2 = A.Item1
  OR T.Part1 = A.Item2
  OR T.Part2 = A.Item2
  )

我正在寻找什么结果:

NAME    PART1       PART2       ITEM1       ITEM2

ABC     FirstABC    SecondABC   FirstABC    SecondABC
CBA     FirstCBA    SecondCBA   FirstCBA    SecondCBA
DAE     FirstDAE    SecondDAE   FirstDAE    SecondDAE
EDA     FirstEDA    SecondEDA   FirstEDA    SecondEDA

2 个答案:

答案 0 :(得分:0)

您可以按所有字段进行分组,并添加一个count = 1的having子句。

SELECT name, part1, part2, item1, item2
FROM TOMATCH as T
LEFT JOIN AGAINST as A
ON (
 T.Part1 = A.Item1
 OR T.Part2 = A.Item1
 OR T.Part1 = A.Item2
 OR T.Part2 = A.Item2
 )
group by name, part1, part2, item1, item2
having count(*) = 1

请参阅SqlFiddle

答案 1 :(得分:0)

在加入TOMATCH之前,将重复项从AGAINST中过滤掉。

UPDATE t
  SET UniqueMatch = ItemNumber
FROM TOMATCH t
INNER JOIN (
  SELECT Item1, Item2, MIN(ItemNumber) AS ItemNumber
  FROM AGAINST
  GROUP BY Item1, Item2
  HAVING COUNT(*) = 1
) a ON (Item1 = Part1 AND Item2 = Part2)