Sql 比较同一表格中的计数数据

Sql 比较同一表格中的计数数据,sql,sql-server,Sql,Sql Server,我使用的是Microsoft SQL Server 2008 R2,我正在尝试比较我运行的以下同一查询的计数结果: select e.JobTitle, COUNT(p.BusinessEntityID) [NO. of persons] from AdventureWorks2008.person.Person p with (Nolock) join AdventureWorks2008.HumanResources.Employee e with (n

我使用的是Microsoft SQL Server 2008 R2,我正在尝试比较我运行的以下同一查询的计数结果:

select 
    e.JobTitle,
    COUNT(p.BusinessEntityID) [NO. of persons]
from 
    AdventureWorks2008.person.Person p with (Nolock)
join 
    AdventureWorks2008.HumanResources.Employee e with (nolock) on e.BusinessEntityID = p.BusinessEntityID
group by 
    e.JobTitle
我得到了如下预期结果:

JobTitle                        NO. Of persons
Accountant                                   2
Accounts Manager                             1
Accounts Payable Specialist                  2
Accounts Receivable Specialist               3
Application Specialist                       4
Assistant to the Chief Financial Officer     1
Benefits Specialist                          1
Buyer                                        9
Chief Executive Officer                      1
Chief Financial Officer                      1
Control Specialist                           2
Database Administrator                       2
Design Engineer                              3
Document Control Assistant                   2
Document Control Manager                     1
Engineering Manager                          1
我现在要做的是显示这些结果中的职务和计数,其中计数相同,但职务不相同

买方基本上不会被退回,因为没有其他组的计数为9

但首席财务官助理、福利专家等将被退回,因为有许多职位的数量为1

最简单、最有效的方法是什么?非常感谢。

您可以使用连接搜索具有相同计数但不同职务的其他行:

; with  List as 
        (
        ... your query here ...
        )
select  *
from    List l1
join    List l2
on      l1.[NO. of persons] = l2.[NO. of persons]
        and l1.JobTitle > l2.JobTitle -- Filter out duplicates

您可以使用cte执行此操作:

with cte as(select e.JobTitle,
                   COUNT(p.BusinessEntityID) [NO. of persons]
            from AdventureWorks2008.person.Person p with (Nolock)
            join AdventureWorks2008.HumanResources.Employee e with (nolock) on e.BusinessEntityID = p.BusinessEntityID
            group by e.JobTitle)

select * from cte c1
where exists(select * from cte c2 
             where c2.[NO. of persons] = c1.[NO. of persons] and 
                   c2.JobTitle <> c1.JobTitle)

您可以为此使用窗口功能:

select *
from (select e.JobTitle,
             COUNT(p.BusinessEntityID) as [NO. of persons],
             COUNT(*) OVER (PARTITION BY COUNT(*)) as count_with_count
     from AdventureWorks2008.person.Person p with (Nolock) join 
          AdventureWorks2008.HumanResources.Employee e with (nolock) 
          on e.BusinessEntityID = p.BusinessEntityID
     group by e.JobTitle
    ) jt
where count_with_count > 1
order by count_with_count;

设置-不建议在任何地方都使用此选项-恰恰相反!这是我的习惯,因为我会因为不使用它而被钉死。很多地方都有查询规则,我们在这件事上没有发言权。谢谢,这就是我想要的。