SQL - 从UNION ALL查询中选择Duplicates

时间:2014-03-24 08:47:21

标签: sql-server duplicates union-all

我正在使用UNION ALL编写4个查询,并按字段1对它们进行排序。

SELECT Field1,Field2,Field3,Field4
FROM table1 

UNION ALL

SELECT Field1,Field2,Field3,Field4
FROM table2 

UNION ALL


SELECT Field1,Field2,Field3,Field4
FROM table3 

UNION ALL

SELECT Field1,Field2,Field3,Field4
FROM table4 

ORDER BY Field1

我想仅返回field1出现两次的行。

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

SELECT Field1, Field2, Field3, Field4, count(*) from (
    ... your query ...
)
GROUP BY Field1, Field2, Field3, Field4
HAVING count(*)=2

(这是Oracle语法,我希望这也适用于sql server)。

或者,如果您想要Field1出现两次的所有行,但Field2,Field3和Field4可能相同或可能不同:

SELECT Field1, Field2, Field3, Field4 from (
    ... your query ...
) where Field1 in (
    SELECT Field1 from (
        SELECT Field1, count(*) from (
            ... your query ...
        )
        GROUP BY Field1
        HAVING count(*) = 2
    )
)

(再次使用Oracle语法)。