我使用的是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份。
做这件事最简单和最有效的方法是什么?先谢了。
发布于 2015-06-14 18:03:27
你可以用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)发布于 2015-06-14 18:02:01
您可以使用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发布于 2015-06-14 18:09:36
您可以为此使用窗口函数:
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;https://stackoverflow.com/questions/30832669
复制相似问题