我正在寻找一种有效的方法来排除SELECT
语句WHERE
中的行。返回多行,并且某列的值相同。
具体来说,我选择了一堆帐户,但需要排除多个帐户,并且相同的SSN关联。
答案 0 :(得分:12)
这将返回所有正好有1行的SSN
select ssn,count(*)
from SomeTable
group by ssn
having count(*) = 1
这将返回所有超过1行的SSN
select ssn,count(*)
from SomeTable
group by ssn
having count(*) > 1
您的完整查询将是这样的(将在SQL Server 7及更高版本上运行)
select a.* from account a
join(
select ssn
from SomeTable
group by ssn
having count(*) = 1) s on a.ssn = s.ssn
答案 1 :(得分:6)
对于SQL 2005或更高版本,您可以尝试:
WITH qry AS
(
SELECT a.*,
COUNT(*) OVER(PARTITION BY ssn) dup_count
FROM accounts a
)
SELECT *
FROM qry
WHERE dup_count = 1
对于SQL 2000和7:
SELECT a.*
FROM accounts a INNER JOIN
(
SELECT ssn
FROM accounts b
GROUP BY ssn
HAVING COUNT(1) = 1
) b ON a.ssn = b.ssn
答案 2 :(得分:1)
SELECT *
FROM #Temp
WHERE SSN NOT IN (SELECT ssn FROM #Temp GROUP BY ssn HAVING COUNT(ssn) > 1)
答案 3 :(得分:0)
谢谢大家的详细建议。完成所有操作后,我需要使用相关子查询。从本质上讲,这就是我必须要做的事情:
SELECT acn, ssn, [date] FROM Account a
WHERE NOT EXISTS (SELECT 1 FROM Account WHERE ssn = a.ssn AND [date] < a.[date])
希望这有助于某人。
我从来没有更新过这个...... 在我的最终提交中,我通过左连接来实现这一目的以提高效率(相关的子查询是不可接受的,因为它需要花费大量的时间来运行,检查每个记录超过150K其他人。)
以下是解决我的问题所必须做的事情:
SELECT acn, ssn
FROM Account a
LEFT JOIN (SELECT ssn, COUNT(1) AS counter FROM Account
GROUP BY ssn) AS counters
ON a.ssn = counters.ssn
WHERE counter IS NULL OR counter = 0