如何在union all select语句中处理sql中的重复项

时间:2015-12-29 12:58:30

标签: sql sql-server sql-server-2012

例如,如果有:

SELECT 'A@G.com' AS Email, 2 AS Somenumber, 3 AS Number
UNION ALL
SELECT 'A@G.com' AS Email, 2 AS Somenumber, 5 AS Number
UNION ALL
SELECT 'z@y.com' AS Email, 1 AS Somenumber, 6 AS Number

而不是:

enter image description here

我想得到:

enter image description here

3 个答案:

答案 0 :(得分:1)

SELECT Email, Somenumber, Number
FROM (
    SELECT *, RowNum = ROW_NUMBER() OVER (PARTITION BY Email ORDER BY Number DESC)
    FROM (
        VALUES
            ('A@G.com', 2, 3),
            ('A@G.com', 2, 5),
            ('z@y.com', 1, 6)
    ) t(Email, Somenumber, Number)
) t
WHERE RowNum = 1

输出 -

Email   Somenumber  Number
------- ----------- -----------
A@G.com 2           5
z@y.com 1           6

答案 1 :(得分:0)

看起来你每封电子邮件只有一行。你可以这样做:

; with  all_rows as
        (
        ... your union query here ...
        )
, with  numbered_rows as
        (
        select  row_number() over (partition by email order by somenumber) as rn
        ,       *
        from    all_rows
        )
select  email
,       somenumber
,       number
from    numbered_rows
WHERE   rn = 1

答案 2 :(得分:0)

通常当我需要解决这样的问题时,我会使用Devart解决方案,只是在我的脑海中以同样的方式工作 但这里提供了更好的执行计划的替代解决方案

select  Email, max(Somenumber), max(Number) from (
SELECT 'A@G.com' AS Email, 2 AS Somenumber, 3 AS Number
UNION ALL
SELECT 'A@G.com' AS Email, 2 AS Somenumber, 5 AS Number
UNION ALL
SELECT 'z@y.com' AS Email, 1 AS Somenumber, 6 AS Number
) A
group by Email

enter image description here