选择子查询中存在的内容

时间:2015-10-13 01:10:18

标签: sql sql-server sql-server-ce

我想计算具有重复值的记录数,然后获取与其相关的各种其他数据。像这样:

500

但我收到错误SELECT Id, Name, PhoneNumber, Code, CodeCount from Person WHERE Code IN (SELECT Code, COUNT(Code) AS CodeCount FROM Person GROUP BY Code HAVING COUNT(Code) > 1);

我如何使这项工作?

4 个答案:

答案 0 :(得分:2)

注意:这不适用于SQL Server CE,但它适用于SQL Server 2005 +。

另一种解决方法是使用窗口函数:

select p.*
from (select p.*, count(*) over (partition by code) as cnt
      from person p
     ) p
where cnt > 1;

因为in同时需要聚合和连接(隐含地因为in),所以此版本通常会有更好的性能。它还可以使用person(code)上的索引。

答案 1 :(得分:1)

您正在执行“Code IN (...)”,但子查询返回两列而不是一列。

从子查询中删除其他列。

您无需返回计数。即使您未在子查询中返回该列,HAVING子句也将起作用。

SELECT Id, Name, PhoneNumber, Code, CodeCount from Person
WHERE Code IN (SELECT Code
           FROM Person
           GROUP BY Code
           HAVING COUNT(Code) > 1);

答案 2 :(得分:1)

这对您有用

    SELECT Id, Name, PhoneNumber, Code, COUNT(Code) AS 'CodeCount' 
    from Person WHERE Code IN (SELECT Code FROM Person) 
    GROUP BY Id, Name, PhoneNumber, Code HAVING COUNT(Code) > 1;

答案 3 :(得分:1)

SQL 2015+: SELECT P.Id, P.Name, P.PhoneNumber, P.Code, Q.CodeCount from Person P CROSS APPLY (SELECT Id, COUNT(Code) OVER(PARTITION BY Code) AS CodeCount FROM Person) AS Q WHERE P.Id = Q.Id AND Q.CodeCount > 1