比较来自同一表的计数数据

时间:2015-06-14 17:54:34

标签: 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 (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。

最简单,最有效的方法是什么?谢谢你。

3 个答案:

答案 0 :(得分:2)

您可以使用cte:

执行此操作
<uses-permission>

答案 1 :(得分:0)

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

; 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

答案 2 :(得分:0)

您可以使用窗口功能:

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;