选择每个实体的最大值

时间:2017-09-02 00:43:08

标签: sql sql-server tsql

在Microsoft SQL Server中,我有一个包含EmployeeID,Category和Amount列的表。如何才能显示每个员工的金额最高的类别?

数据示例:

EmployeeID   Category    Amount
11111        Vacation    4
11111        Personal    2
11111        Holiday     3
22222        Vacation    1
22222        Personal    3
22222        Holiday     2
33333        Personal    5
33333        Holiday     1
33333        Vacation    3
33333        Unspecified 3

结果:

EmployeeID   Category   Amount
11111        Vacation   4
22222        Personal   3
33333        Personal   5

4 个答案:

答案 0 :(得分:2)

另一个选项是 WITH TIES 子句

示例

Select Top 1 with Ties *
 From  YourTable
 Order By Row_Number() over (Partition By EmployeeID Order By Amount Desc)

<强>返回

enter image description here

或使用Row_Number()和CTE

;with cte as (
Select *
      ,RN = Row_Number() over (Partition By EmployeeID Order By Amount Desc)
 From  YourTable
)
Select EmployeeID
      ,Category
      ,Amount
 From cte where RN=1

答案 1 :(得分:2)

以下是一些不同的选择。根据可用的索引,它们中的任何一个都可以比另一个更好地执行,所以这三个都值得在您的环境中进行测试。

require 'rest_client'

RestClient.post("https://localhost:1337/uploads/image.jpg",
  :filename => File.new("C:\\Users\\ruby\\image.jpg", 'rb'))

所有3个产生相同的结果......

<div class="ui container">
  <div class="ui four cards stackable">
   <div class="teal card">Card1</div>
   <div class="teal card">Card2</div>
   <div class="teal card">Card3</div>
   <div class="teal card">Card4</div>
   <div class="teal card">Card5</div>
   <div class="teal card">Card6</div>
 </div>
</div> 

答案 2 :(得分:0)

使用EXISTS / NOT EXISTS

select *
from Employees
where not exists
  (select * from Employees as E
   where E.EmployeeID=Employees.EmployeeID -- join condition
     and E.Amount>Employees.Amount) -- filter condition

答案 3 :(得分:0)

SELECT EmployeeID, Category, Amount
FROM (select *, ROW_NUMBER() OVER (PARTITION BY EmployeeID 
      ORDER BY EmployeeID as rn ,Amount desc)
FROM getmaxdata) x WHERE x.rn =1