如何在ORACLE和SQL SERVER中编写查询以获取具有最多状态的记录?

时间:2012-03-30 12:31:26

标签: sql-server oracle tsql

对于下表

tenant_id | status_id
----------------------
   3      |   6
---------------------
   5      |   7
---------------------
   7      |   7
--------------------
   3      |   7
-------------------
   3      |   7
--------------------
   5      |   7

我们可以看到:

  • tenant_id = 3有1条记录,status_id = 6
  • tenant_id = 5有2条记录,status_id = 7
  • tenant_id = 7有1条记录,status_id = 7
  • tenant_id = 3有2条记录,status_id = 7

对于给定的STATUS_ID_PARAM,我想让所有拥有STATUS_ID_PARAM记录最多的租户。 对于上面的示例,对于STATUS_ID_PARAM = 7,查询应返回2条记录:

   tenant_id | status_id
   --------------------
      3      |   7
   --------------------
      5      |   7

因为这些租户的记录最多(每个2个),status_id = 7。

我尝试过这样的事情,但我不知道如何继续,或者可能还有另一种方式:

select tenant_id, count(status_id) s
from candidate
where status_id = STATUS_ID_PARAM 
group by tenant_id, status_id

4 个答案:

答案 0 :(得分:4)

这适用于Oracle和SQL Server

select tenant_id, s
from
  (       
    select tenant_id,
           count(*) as s,
           rank() over(order by count(*) desc) as rn
    from candidate
    where status_id = 7
    group by tenant_id
  ) T
where rn = 1;

(在SQL Server 2005-> 2012和Oracle 11g R2上测试)

答案 1 :(得分:0)

select tenant_id, count(status_id) s
from candidate
where status_id = STATUS_ID_PARAM 
group by tenant_id, status_id
having count(status_id) = (select max(count(status_id)) from candidate)

答案 2 :(得分:0)

试试这个

select tenant_id, count(status_id) s
from candidate
where status_id = STATUS_ID_PARAM 
AND count(status_id) = MAX(count(status_id))
group by tenant_id, status_id

答案 3 :(得分:0)

我编辑了答案:)

select tenant_id, count(status_id) s
from candidate can
where status_id = 7
group by tenant_id, status_id
having COUNT(status_id) 
in 
(
select top 1 count(status_id) from candidate 
group by status_id,tenant_id
order by COUNT(status_id) desc
)