如何确定SQL中每个类别的最大值?

时间:2011-04-05 12:56:30

标签: sql sql-server-2008 stored-procedures

我的表格有如下记录:

ID          EmpID           EffectiveDate     PayElement  Amount   ComputeType      AddDeduction
    42  ISIPL001    2010-04-16 00:00:00.000 Basic     8000.00   On Attendance   Addition
    43  ISIPL001    2010-04-01 00:00:00.000 Con       2000.00   On Attendance   Addition
    44  ISIPL001    2010-04-01 00:00:00.000 HRA       2000.00   On Attendance   Addition
    54  ISIPL001    2011-01-01 00:00:00.000 Basic    15000.00   On Attendance   Addition
    55  ISIPL001    2011-01-01 00:00:00.000 Con       6000.00   On Attendance   Addition
    57  ISIPL001    2011-01-01 00:00:00.000 HRA       6000.00   On Attendance   Addition
    61  ISIPL001    2010-07-10 00:00:00.000 Basic    12000.00   On Attendance   Addition
    66  ISIPL001    2010-07-10 00:00:00.000 HRA       4200.00   On Attendance   Addition
    68  ISIPL001    2010-07-10 00:00:00.000 Con       5600.00   On Attendance   Addition

我希望结果显示如下:

即对于我的数据库中可用的每个薪资元素,我需要记录每个薪资元素的最大日期。

所以我的输出应该如下所示:

54  Basic 15000
55  Con    6000
57  HRA    6000

6 个答案:

答案 0 :(得分:2)

试试这个:

SELECT  ID, 
        PayElement, 
        Amount
  FROM  (
        SELECT a.*,
             RANK() OVER(PARTITION BY PayElement ORDER BY EffectiveDate DESC) AS rn
        FROM <YOUR_TABLE> a 
        )   a
WHERE rn = 1                

答案 1 :(得分:1)

;with cte as
(
  select *,
    row_number() over(partition by PayElement order by EffectiveDate desc) as rn
  from YourTable
)    
select
  ID,
  PayElement,
  Amount
from cte
where rn = 1

答案 2 :(得分:1)

试试这个。

select
  T.ID,
  T.PayElement,
  T.Amount
from
  Test T inner join (select MAX(T_DATE.EffectiveDate) as MAX_DATE, T_DATE.PayElement from Test T_DATE group by T_DATE.PayElement) T_DATE on (T.PayElement = T_DATE.PayElement) and (T.EffectiveDate = T_DATE.MAX_DATE)
order by
  T.ID

答案 3 :(得分:0)

Select  a.Id, 
        a.PayElement,
        a.Amount

From dbo.YourTable a
Join 
(
Select  PayElement,
        Max(EffectiveDate) as[MaxDate]

From  dbo.YourTable
Group By PayElement
)b on a.PayElement = b.PayElement
        And a.EffectiveDate = b.MaxDate

答案 4 :(得分:0)

尝试类似

的内容
Select 
   a.ID, a.PayElement, a.Amount 
From MyTable a
Inner Join (
   Select PayElement, max(EffectiveDate) as MaxDate From MyTable Group By PayElement
) sub on a.EffectiveDate = sub.MaxDate and a.PayElement = sub.PayElement

答案 5 :(得分:0)

select 
    Id, PayElement, Amount
from
    YourTable a
inner join
    (select 
        Id, PayElement, max(EffectiveDate) as EffectiveDate
    from 
        YourTable
    group by
        PayElement, Id) b
on 
    a.Id = b.Id