Sql 获取没有重复数据的值
我有这样一个问题:Sql 获取没有重复数据的值,sql,sql-server,tsql,Sql,Sql Server,Tsql,我有这样一个问题: SELECT P.LegacyKey ,D.DesignNumber FROM tbl1 AS [SO] GROUP BY D.DesignNumber,P.LegacyKey ORDER BY LegacyKey select t2.LegacyKey, t2.DesignNumber from ( select t.LegacyKey from tbl1 t group by t.LegacyKey
SELECT
P.LegacyKey
,D.DesignNumber
FROM tbl1 AS [SO]
GROUP BY D.DesignNumber,P.LegacyKey
ORDER BY LegacyKey
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
它返回的值如下:
+-----------+--------------+
| 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
我做错了什么?你需要这样的东西:
SELECT
P.LegacyKey
,D.DesignNumber
FROM tbl1 AS [SO]
GROUP BY D.DesignNumber,P.LegacyKey
ORDER BY LegacyKey
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 *
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
您可以简单地执行以下操作:
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;
不需要子查询。第一个查询有三个输出列,但结果集只显示两个。有些不正确。抱歉,修复了@searle1986tbl1是否有主键,然后执行内部选择:)