Sql 最大值的最小值

Sql 最大值的最小值,sql,tsql,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-06-19 我很难把最小值和最大值结合起来,来计算查询。有什么想法吗?我想这就是你想要的: select top 1 * from table

考虑以下结果

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-06-19


我很难把最小值和最大值结合起来,来计算查询。有什么想法吗?

我想这就是你想要的:

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

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


我认为,这样做应该为每个客户找到最大值的最小值:

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

不完全是,如果我做了TOP1,我只从一个客户那里得到结果,我需要对整个客户运行这个table@BelgoCanadian . . . 在提问时,你应该努力包含所有相关信息。
select top 1 *
from ( select * ,
              rank = row_number() over (
                       order by DateTime2 desc ,
                                DateTime1 asc
                       )
     ) t
where t.rank = 1