SQL,选择最大日期,如果两个结果有最大日期,请选择具有最大权重的日期

时间:2014-06-21 12:18:41

标签: sql

ID | DATE_I                 | Weight
1  | 10/04/2014 08:13:05  | 10
2  | 02/04/2014 08:13:05  | 15
3  | 08/04/2014 08:13:05  | 10
4  | 13/04/2014 08:13:05  | 12
5  | 13/04/2014 08:13:05  | 10

我的SQL请求请求应该给我第4行。

select id, max(DATE_I)
from MyTable m
where m.Weight > (select m2.Weight from MyTable m2 having max(DATE_I)); 

2 个答案:

答案 0 :(得分:1)

试试这个:

select y.ID, x.maxdate, x.maxweight
from 
(
  select a.maxdate, Max(b.Weight) as maxweight
  from 
  (
    select max(date_I) as maxdate
    from mytable
  )a 
  inner join mytable b on a.maxdate = b.date_I
  group By a.maxdate
) x inner join mytable y on x.maxweight = y.weight

Demo Here

答案 1 :(得分:1)

DATE_IWeight降序排序您的行并获取第一行。

SQL Server的示例代码。

select top (1) ID, DATE_I, Weight
from mytable
order by DATE_I desc, Weight desc;