我必须获得查询结果中的第二大计数

时间:2012-12-06 07:54:05

标签: sql sql-server sql-server-2008

我正在使用测试数据库Advetureworks,我希望得到结果中第二高的数,但我没有得到它。

我必须对以下查询进行哪些更改才能获得所需的结果?

select pa.City,psp.Name,COUNT(he.EmployeeID) as emp_count
from HumanResources.EmployeeAddress hea
join HumanResources.Employee he on he.EmployeeID=hea.EmployeeID
join Person.Contact pc on pc.ContactID=he.ContactID
join Person.Address pa on pa.AddressID=hea.AddressID
join Person.StateProvince psp on psp.StateProvinceID=pa.StateProvinceID
where COUNT(he.EmployeeID) < (select max(count(he.employeeid)) from HumanResources.Employee)

group by pa.City,psp.Name

2 个答案:

答案 0 :(得分:5)

你可以使用排名功能,试试这样:

;WITH a AS (
    select pa.City,psp.Name,COUNT(he.EmployeeID) as emp_count
    from HumanResources.EmployeeAddress hea
    join HumanResources.Employee he on he.EmployeeID=hea.EmployeeID
    join Person.Contact pc on pc.ContactID=he.ContactID
    join Person.Address pa on pa.AddressID=hea.AddressID
    join Person.StateProvince psp on psp.StateProvinceID=pa.StateProvinceID
    group by pa.City,psp.Name   
), b AS (
    SELECT  *,
            ROW_NUMBER() OVER (ORDER BY emp_count DESC) num
    FROM    a
)
SELECT  *
FROM    b
WHERE   b.num = 2

答案 1 :(得分:4)

我知道有一种ROW_NUMBER的做法,就像Ivan G发布的一样,但我永远不会记住语法,所以这里的方法略有不同:

with top_cities (City, Name, emp_count) as
(
  select top 2
    pa.City,psp.Name,COUNT(he.EmployeeID) as emp_count
  from 
    HumanResources.EmployeeAddress hea
    join HumanResources.Employee he on he.EmployeeID=hea.EmployeeID
    join Person.Contact pc on pc.ContactID=he.ContactID
    join Person.Address pa on pa.AddressID=hea.AddressID
    join Person.StateProvince psp on psp.StateProvinceID=pa.StateProvinceID        
  group by 
    pa.City,psp.Name
  order by 
    emp_count desc
)
select top 1 * from top_cities order by emp_count asc