最小值的最小值

时间:2014-05-20 21:42:38

标签: sql tsql

考虑以下结果

Datetime1   DateTime2   Customer
2013-06-19  2011-03-30  IP003779    
2014-04-24  2011-03-30  IP003779    
2011-03-30  2009-03-18  IP003779

我需要从第二列的最大值中选择第一列的最小值。 - > 2013年6月19日

我很难搞清楚查询,将min和max结合起来。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

我认为这就是你想要的:

select top 1 *
from table t
order by DateTime2 desc, DateTime1 asc;

编辑:

如果您需要为所有客户执行此操作,请使用row_number()

select t.*
from (select t.*,
             row_number() over (partition by customer order by datetime2 desc, datetime1 asc) as seqnum
      from table t
     ) t
where seqnum = 1;

答案 1 :(得分:1)

我认为应该做的就是找到每个客户的最大最小值:

select Customer        =      t.Customer    ,
       DateTime2_Max   =      t.dt2Max      ,
       DateTime1_Min   = min( x.DateTime1 )
from ( select Customer = Customer ,
              dt2Max   = max( DateTime2 ) 
       from some_table
       group by Customer
     ) t
join some_table x on x.Customer  = t.Customer
                 and x.DateTime2 = t.dt2Max
group by t.Customer ,
         t.dt2Max

如果你想整体看一下表格,那就更简单了:

select DateTime2_Max =      t.dt2Max      ,
       DateTime1_Min = min( x.DateTime1 )
from ( select dt2Max   = max( DateTime2 ) 
       from some_table
     ) t
join some_table x on x.DateTime2 = t.dt2Max
group by t.dt2Max

您还可以使用窗口函数。由客户打破,它看起来像:

select *
from ( select * ,
              rank = row_number() over (
                       partition by Customer
                       order by DateTime2 desc ,
                                DateTime1 asc
                       )
     ) t
where t.rank = 1
order by 1,2,3

再次,如果你整体看一下表格会更简单:

select top 1 *
from ( select * ,
              rank = row_number() over (
                       order by DateTime2 desc ,
                                DateTime1 asc
                       )
     ) t
where t.rank = 1