在列上选择具有不同值的重复记录

时间:2018-03-23 18:39:34

标签: sql sql-server

表:

**URL       | Answer**
google      |  NULL
google      |  NULL
google      |  NULL
yahoo       |  Yes
hotmail     |  NULL
hotmail     |  No

我想选择所有具有相同网址但只有Answer NULL的记录,在这种情况下,google&空值。如果URL有一个NULL&不,或是,那些我不需要的那些就像hotmail那样。

SELECT DISTINCT URL
FROM Table
WHERE URL IN (
    SELECT URL
    FROM Table
    WHERE Answer IS NULL
    GROUP BY URL
    HAVING Count(*)  >= 1   
    );

4 个答案:

答案 0 :(得分:0)

由于HAVING Count(*) >= 1您不需要计算。

create table tbl (URL nvarchar(max), Answer varchar(10));
insert into tbl values
('google', NULL),
('google', NULL),
('google', NULL),
('yahoo', 'Yes'),
('hotmail', NULL),
('hotmail', 'No');
GO
6 rows affected
SELECT URL
FROM   tbl
WHERE  Answer IS NULL
GROUP BY URL
HAVING COUNT(*) > 1
GO
| URL    |
| :----- |
| google |

dbfiddle here

或者只是为了确保所有行都为空:

SELECT t1.URL
FROM   tbl t1
WHERE  t1.Answer IS NULL
AND    NOT EXISTS (SELECT 1 
                   FROM   tbl
                   WHERE  URL = t1.URL
                   AND    Answer IS NOT NULL)
GROUP BY t1.URL
GO
| URL    |
| :----- |
| google |

dbfiddle here

答案 1 :(得分:0)

您的查询只需DISTINCT即可。无需使用HAVING Count(*) >= 1或子查询

SELECT DISTINCT URL
FROM Table
WHERE Answer IS NULL

会给你以下输出

google
hotmail

条件WHERE Answer IS NULL将为您提供NULL答案,Distinct将确保所有网址都是唯一的。

答案 2 :(得分:0)

如果您想要所有带NULL的URL,请执行以下操作:

    SELECT DISTINCT URL
FROM Table
WHERE URL IS NULL

如果你想要计数:

SELECT DISTINCT URL, count(*) as count
    FROM Table
    WHERE URL IS NULL
GROUP BY URL

答案 3 :(得分:0)

我认为这很好

declare @T table (URL nvarchar(max), Answer varchar(10));
insert into @T values
('google', NULL),
('google', NULL),
('google', NULL),
('yahoo', 'Yes'),
('hotmail', NULL),
('hotmail', 'No');
select t.URL 
from @T t
group by t.URL
having max(t.Answer) is null 
   and count(*) > 1;