在SQL Server

时间:2017-02-23 08:03:20

标签: sql sql-server group-by distinct having

我需要找到特定组中存在的非相同值。请查看下表Contact

ContactId    FirstName    LastName    Mobile
_________________________________________________

1            Emma         Watsan      9991234567
2            Jhon         Wick        8887654321
1            Emma         Watsan      9990001111

在这里,我需要获取 Emma Watsan ,并且需要找到手机号码是相同的(bool - bit)如果两个手机号码都与1相同,否则{ {1}}。

我尝试了以下查询

0

请帮助我如何找到结果。

3 个答案:

答案 0 :(得分:1)

获取与Emma Watsan相关的信息,你可以

select * from Contact
where ContactId in ( 
  select c.ContactId FROM Contact c 
  group by c.ContactId 
  having  COUNT(*) >1
)

获取具有相同数字的联系人

select c.ContactId,   COUNT(distinct Mobile) FROM Contact c 
group by  c.ContactId
having   COUNT(distinct Mobile)>1 

答案 1 :(得分:1)

使用Count(Distinct [Mobile])获取每ContactId个不同移动纳米数的数量。并使用CASE表达式根据计数提供01。如果count大于1则为0,否则为1。

<强>查询

select t.[Name], case when t.[Mobile] > 1 then 0 else 1 end as [Mobile_Identity] from(
    select ContactId, 
    max([FirstName] + ' ' + [LastName]) as [Name],   
    count(distinct [Mobile]) as [Mobile]
    from contacts
    group by ContactId
)t;

如果您只想检索具有多个手机号码的行,请使用having子句。

select t.[Name], case when t.[Mobile] > 1 then 0 else 1 end as [Mobile_Identity] from(
    select ContactId, 
    max([FirstName] + ' ' + [LastName]) as [Name],   
    count(distinct [Mobile]) as [Mobile]
    from contacts
    group by ContactId
    having count(distinct [Mobile]) > 1
)t;

答案 2 :(得分:1)

我会这样做......(包含数据的样本表变量)

DECLARE @TABLE TABLE (ContactID INT, Firstname VARCHAR(55), Lastname VARCHAR(55), Mobile VARCHAR(55));

INSERT INTO @TABLE VALUES (1, 'Emma', 'Watsan', '9991234567');
INSERT INTO @TABLE VALUES (2, 'Jhon', 'Wick', '8887654321');
INSERT INTO @TABLE VALUES (1, 'Emma', 'Watsan', '9990001111');
INSERT INTO @TABLE VALUES (1, 'Emma', 'Watsan', '9990001111');

SELECT 
     T1.FirstName + ' ' + T1.LastName AS Name
    ,T1.Mobile
    ,MAX(CASE WHEN T2.RowID IS NULL THEN 0 ELSE 1 END) AS Duplicate
FROM 
    (
    SELECT 
         ROW_NUMBER() OVER (ORDER BY FirstName,LastName, Mobile) AS RowID
        ,*
    FROM @TABLE
    ) T1
LEFT JOIN
    (
    SELECT
         ROW_NUMBER() OVER (ORDER BY FirstName,LastName, Mobile) AS RowID
        ,*
    FROM @TABLE
    ) T2
    ON T1.ContactID = T2.ContactID
    AND T1.Mobile = T2.Mobile
    AND T1.RowID <> T2.RowID
GROUP BY T1.FirstName + ' ' + T1.LastName, T1.Mobile
;

如果实际表已经有行号,则可以跳过row_number()函数,并在其位置使用表的实际行ID。

在这里的例子中,Emma Watsan有两次相同的号码(故意),另一个号码只在表格中显示一次。重复的手机号码已标记为(Duplicate = 1),但其他号码未标记。