获取没有重复数据的值

问题描述 投票:0回答:3

我有这样的查询:

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 

我究竟做错了什么?

sql sql-server tsql
3个回答
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;

不需要子查询。


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
)

0
投票

你可以试试这个

注意 - 这是未经测试的

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
© www.soinside.com 2019 - 2024. All rights reserved.