组合3个表,其中2列的组合不是唯一的

时间:2014-05-12 22:17:20

标签: sql select union

具有相同列的表有3个(将来最多6个)。

我需要统一它们,即在同一列上联合。除此之外 - 基于2列组合,行不应是唯一的!网上有几个示例,但所有示例都显示了如何根据一列 排除唯一列值。在我的情况下,有2列(Col1和Col2组合)。

以下是原理图:

enter image description here

enter image description here

以下是我想象的最终查询(对于3个表格)的样子:

SELECT
*
FROM
(
SELECT * FROM table1
UNION
SELECT * FROM table2
UNION
SELECT * FROM table3
)
GROUP BY
Col1, Col2
HAVING
COUNT (*) > 1

什么是正确的方法?

P.S。 FYI单柱解决方案

Multiple NOT distinct

How to select non "unique" rows

How to Select Every Row Where Column Value is NOT Distinct

修改

我使用了已接受答案中的代码并添加了其他搜索条件:

  ON (SOUNDEX(Merged.[name_t1]) = SOUNDEX(Multiples.[name_t1]) OR Merged.[name_t1] LIKE '%' + Multiples.[name_t1] + '%' OR Multiples.[name_t1] LIKE '%' + Merged.[name_t1] + '%')
  AND (SOUNDEX(Merged.[name_t2]) = SOUNDEX(Multiples.[name_t2]) OR Merged.[name_t2] LIKE '%' + Multiples.[name_t2] + '%' OR Multiples.[name_t2] LIKE '%' + Merged.[name_t2] + '%')

搜索col1和col2:

-by SOUNDEX

-by col1 like(col1 from other table)

-by(来自其他表的col1),如col1

1 个答案:

答案 0 :(得分:1)

以下是基于CTE的方法的基础知识:

With Merged AS
(  -- CTE 1 : All Data in one table
 SELECT * FROM table1
  UNION ALL
 SELECT * FROM table2
  UNION ALL
 SELECT * FROM table3
) 
, Multiples AS
(  -- CTE 2 : Group by the fields in common
 SELECT   Col1, Col2
 FROM Merged
 GROUP BY Col1, Col2
 HAVING Count(*)>1 -- only want Groups of 2 or more
)
SELECT
  Merged.*
FROM Merged INNER JOIN Multiples
  -- Only return rows from Merged if they're in Multiples
   ON Merged.[Col1]=Multiples.[Col1]
  AND Merged.[Col2]=Multiples.[Col2]

这样的东西适用于我自己的示例MS-SQL数据,看起来SQLite语法是相同的。 HTH!