如何仅显示每个的最大计数结果

时间:2017-05-17 17:05:22

标签: sql

我在显示的每台计算机上都有使用nb on longon(totalcount)的vuser。

我想只显示具有每个vuser的最大总计数的vcomputer

这样,只会显示具有max logon的vcomputer

感谢

logcat

Example

1 个答案:

答案 0 :(得分:0)

在SQL Server中:

top with tiesrow_number()

一起使用
select top 1 with ties
    [vUser]
  , [vcomputer]
  , vFullName
  , count(*) as totalCount
from [PRD_TechnoWin].[dbo].[v_Logonstats_PFB]
where vComputer not like '%-VX%'
  and vComputer not like '%-V%'
  and v_Logonstats_PFB.vComputer not like '%XDAS%'
  and v_Logonstats_PFB.vComputer not like '%XDDS%'
  and v_Logonstats_PFB.vComputer not like 'VM%'
  and v_Logonstats_PFB.vComputer not like '%TEST%'
  and v_Logonstats_PFB.vComputer not like '%FOR%'
  and v_Logonstats_PFB.vComputer not like '%GPW%%'
  and v_Logonstats_PFB.vComputer not like '%PW%'
  and v_Logonstats_PFB.vComputer not like '%DW1%'
  and v_Logonstats_PFB.vComputer not like '%GRP-PFB-32BIT%'
  and vDateTimeLogon > GETDATE() - 45
group by 
    vComputer
  , vUser
  , vFullName
order by row_number() over (partition by vUser, vcomputer order by count(*) desc)

common table expressionrow_number()

with cte as (
    select 
        [vUser]
      , [vcomputer]
      , vFullName
      , count(*) as totalCount
      , row_number() over (partition by vUser, vcomputer order by count(*) desc)
    from [PRD_TechnoWin].[dbo].[v_Logonstats_PFB]
    where vComputer not like '%-VX%'
      and vComputer not like '%-V%'
      and v_Logonstats_PFB.vComputer not like '%XDAS%'
      and v_Logonstats_PFB.vComputer not like '%XDDS%'
      and v_Logonstats_PFB.vComputer not like 'VM%'
      and v_Logonstats_PFB.vComputer not like '%TEST%'
      and v_Logonstats_PFB.vComputer not like '%FOR%'
      and v_Logonstats_PFB.vComputer not like '%GPW%%'
      and v_Logonstats_PFB.vComputer not like '%PW%'
      and v_Logonstats_PFB.vComputer not like '%DW1%'
      and v_Logonstats_PFB.vComputer not like '%GRP-PFB-32BIT%'
      and vDateTimeLogon > GETDATE() - 45
    group by 
        vComputer
      , vUser
      , vFullName
)
select vUser, vComputer, vFullName, TotalCount
from cte
where rn = 1