获取没有重复数据的值

时间:2019-03-04 23:07:30

标签: sql sql-server tsql

我有这样的查询:

SELECT
      P.LegacyKey
      ,D.DesignNumber
      FROM tbl1 AS [SO]
 GROUP BY D.DesignNumber,P.LegacyKey
 ORDER BY LegacyKey

它返回的值如下:

+-----------+--------------+
| LegacyKey | DesignNumber |
+-----------+--------------+
|     17134 |            1 |
|     17134 |            2 |
|     18017 |            7 |
+-----------+--------------+

我要做的是查找重复的LegacyKeys并仅获取一次存在legacyKey的值,因此我使用HAVING COUNT

SELECT
      P.LegacyKey
      ,D.DesignNumber
      , COUNT([P].[LegacyKey])
      FROM tbl1 AS [SO]
 GROUP BY D.DesignNumber,P.LegacyKey
 HAVING COUNT([P].[LegacyKey])  = 1
 ORDER BY LegacyKey

但这会返回错误的数据,因为它再次返回了LegacyKey = 17134,并且期望的结果是获取LegacyKey存在一次的值。

所以欲望的结果应该只是

  18017 |            7 

我在做什么错了?

3 个答案:

答案 0 :(得分:1)

您可以简单地做到:

SELECT P.LegacyKey, MAX(D.DesignNumber) as DesignNumber
FROM tbl1 AS [SO]
GROUP BY P.LegacyKey
HAVING COUNT(DISTINCT D.DesignNumber) = 1;
ORDER BY LegacyKey;

不需要子查询。

答案 1 :(得分:0)

您需要这样的东西:

select t2.LegacyKey, t2.DesignNumber
from
(
    select t.LegacyKey 
    from tbl1 t
    group by t.LegacyKey 
    having count(t.LegacyKey ) = 1
)x
join tbl1 t2 on x.LegacyKey = t2.LegacyKey

select t2.LegacyKey, t2.DesignNumber
from tbl1 t2
where t2.LegacyKey in
(
    select t.LegacyKey 
    from tbl1 t
    group by t.LegacyKey 
    having count(t.LegacyKey ) = 1
)

答案 2 :(得分:0)

您可以尝试

NB-这未经测试

SELECT  *   
FROM    (
            SELECT
                  P.LegacyKey AS LegacyKey,
                  D.DesignNumber AS DesignNumber,
                  COUNT([P].[LegacyKey]) AS cnt
             FROM tbl1 AS [SO]
             GROUP BY D.DesignNumber,P.LegacyKey
             HAVING COUNT([P].[LegacyKey])  = 1
        ) a
WHERE   COUNT() OVER (PARTITION BY LegacyKey) = 1