根据一个字段查找不重复的记录,不包括空值。

时间:2016-04-21 23:09:33

标签: sql sql-server-2012 conditional

我想在Dat1字段中找到所有唯一记录,但我希望返回每个Null记录。丢弃哪个重复记录并不重要。

示例表:

+----+--------------+
| ID |     Dat1     |
+----+--------------+
|  1 | 11@email.com |
|  2 | 11@email.com |
|  3 | NULL         |
|  4 | NULL         |
|  5 | 99@email.com |
|  6 | 99@email.com |
+----+--------------+

期望的结果:

+----+--------------+
| ID |     Dat1     |
+----+--------------+
|  1 | 11@email.com |
|  3 | NULL         |
|  4 | NULL         |
|  5 | 99@email.com |
+----+--------------+

这可能吗?我尝试了几种带有子查询的方法,但无法完全解决问题。

2 个答案:

答案 0 :(得分:0)

select min(id), dat1 from table where dat1 is not null group by dat1 
union
select id     , dat  from table where dat1 is null

答案 1 :(得分:0)

您可以使用ROW_NUMBER消除非空Dat1的重复项,然后使用UNION ALL添加NULL值:

WITH tbl(Id, Dat1) AS(
    SELECT 1, '11@email.com' UNION ALL
    SELECT 2, '11@email.com' UNION ALL
    SELECT 3, NULL UNION ALL
    SELECT 4, NULL UNION ALL
    SELECT 5, '99@email.com' UNION ALL
    SELECT 6, '99@email.com'
)
SELECT 
    Id, Dat1
FROM (
    SELECT *,
        rn = ROW_NUMBER() OVER(PARTITION BY Dat1 ORDER BY Id)
    FROM tbl
    WHERE Dat1 IS NOT NULL
)t
WHERE rn = 1

UNION ALL

SELECT * FROM tbl WHERE Dat1 IS NULL