[英]Max count SQL Server
I will explain my question with a practical example so that it is easier to visualize the issue. 我将通过一个实际的例子来说明我的问题,以便更轻松地可视化该问题。 I have build this query:
我建立了这个查询:
Select
E.Tipo_Esp, F.Nome, F.Apelido,
count (Ac.id_acto) as total_consultas
from
Especialidade as E
right join
Funcionario as F on F.id_Esp = E.id_Esp
inner join
Acto as Ac on Ac.id_func = F.id_func
inner join
TipoActo as TA on TA.id_Tipo_acto = Ac.id_Tipo_acto
where
TA.Descricao_Acto = 'Consulta'
group by
E.Tipo_Esp, F.Nome, F.Apelido
order by
count(Ac.id_acto) DESC
to arrive to the following result: 得到以下结果:
Tipo_Esp Nome Apelido total_consultas
Ortopedia Maria Antonia 3
Ortopedia Luis Cruz 1
Cirurgia André Martins 2
Cirurgia Diogo Martins 1
However what I need to arrive is this: 但是我需要到达的是:
Tipo_Esp Nome Apelido total_consultas
Ortopedia Maria Antonia 3
Cirurgia André Martins 2
meaning I only need the higher count for each "Tipo_Esp". 这意味着我只需要为每个“ Tipo_Esp”分配更高的计数。 I have tried to apply the max count function with the above query as a subquery but it did went well as expected.
我尝试将上述查询的最大计数功能作为子查询来应用,但它确实按预期进行。 can someone help me with this issue please?
有人可以帮我解决这个问题吗? thanks in advance
提前致谢
You could do this: 您可以这样做:
with orig as (
Select E.Tipo_Esp, F.Nome, F.Apelido, count (Ac.id_acto) as total_consultas from
Especialidade as E
right join Funcionario as F on F.id_Esp = E.id_Esp
inner join Acto as Ac on Ac.id_func = F.id_func
inner join TipoActo as TA on TA.id_Tipo_acto = Ac.id_Tipo_acto
WHERE TA.Descricao_Acto = 'Consulta'
GROUP BY E.Tipo_Esp, F.Nome, F.Apelido
ORDER BY count(Ac.id_acto) DESC
)
select o.*
from orig o
inner join (
select tipo_esp, max(total_consultas) as maxtotal
from orig
group by tipo_esp
) t on o.tipo_esp = t.tipo_esp and o.total_consultas = t.maxtotal
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.