仅查找最大数据记录

时间:2013-07-30 10:29:49

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

我有以下查询

select ROW_NUMBER() over(order by [emp_no] ) as RowId,
       emp_no, 
       pc_ip,
       count(1) as count into #tmp 
  from ip_track
 group by emp_no, pc_ip

 select * 
   from #tmp 
  where emp_no in ('e44920','e39787')

我只选择了2个员工记录作为例子。 此查询将为我提供以下数据

RowId   emp_no  pc_ip   count
790033  E39787  172.29.22.36    1
790034  E39787  172.29.23.48    3
790035  E39787  172.29.23.49    37
790036  E39787  172.29.23.50    724
790037  E39787  172.29.23.53    18
790038  E39787  172.29.23.17    48
790039  E39787  172.29.24.38    325
790040  E39787  172.29.31.183   1
790041  E39787  172.29.23.45    7
790042  E39787  172.29.23.18    5
790043  E39787  172.29.23.34    1
790044  E39787  172.29.22.31    1
790045  E39787  172.29.23.40    2
790046  E39787  172.29.23.55    56
790047  E39787  172.29.22.43    1
790048  E39787  172.29.23.10    2
790049  E39787  172.29.23.58    6
790050  E39787  172.29.23.54    3
790051  E39787  172.29.21.36    25
790052  E39787  172.29.23.43    11
790053  E39787  172.29.24.121   4
846618  E44920  172.29.24.34    1
846619  E44920  172.29.23.55    1292
846620  E44920  172.29.23.34    12
846621  E44920  172.29.23.10    1
846622  E44920  172.29.23.58    2
846623  E44920  172.29.23.40    11
846624  E44920  172.29.23.48    39
846625  E44920  172.29.23.45    1
846626  E44920  172.29.23.50    8
846627  E44920  172.29.23.53    2
846628  E44920  172.29.23.17    7
846629  E44920  172.29.24.38    31
846630  E44920  172.29.21.36    10
846631  E44920  172.29.23.43    14
846632  E44920  172.29.23.54    15

现在我想从不同员工的记录中找到最大数据,以便输出如下所示

RowId   emp_no   pc_ip          count

790036  E39787  172.29.23.50    724
846619  E44920  172.29.23.55    1292

我想获得最大数量数据..我可以这样做,请回复..提前致谢。

2 个答案:

答案 0 :(得分:2)

select * 
 from #tmp B
where emp_no in ('e44920','e39787')
and 
 [Count]=(Select Max([Count] from #tmp A where A.emp_no =B.emp_no )

答案 1 :(得分:1)

select RowId,emp_no,pc_ip from
( 
 select RowId,emp_no,pc_ip,count, row_number() over(partition by emp_no order by count desc) chk
   from #tmp 
  where emp_no in ('e44920','e39787')
) a
where chk = 1