如何通过sql获取组中最大的值

时间:2017-04-26 07:08:28

标签: sql sql-server

我有一个表,表包含OperationDateLotIDNewStatusIDopeTypeId

我想为每一批展示OperationDate(top1)。

我的查询是这样的:

      select a.OperationDate,a.LotID
  FROM  [dbo].[MMwLotOperations]   a
  where   a.LotID in ('L705816008','L704511001')
    GROUP by a.LotID,a.OperationDate 
 having  a.NewStatusID ='Assigned' AND a.opeTypeId = 'Status' 

此查询返回以下数据:

enter image description here

L705816008 很多NewStatusID返回1个数据

L704511001 很多NewStatusID返回2个数据

现在我想展示每一批最大的OperationDate。 怎么办呢?

你可以帮我吗?

感谢。

4 个答案:

答案 0 :(得分:3)

您可以使用MAX获取最长的约会,并从a.OperationDate

中移除Group By
select MAX(a.OperationDate),a.LotID
FROM  [dbo].[MMwLotOperations]   a
where   a.LotID in ('L705816008','L704511001')
        AND a.NewStatusID ='Assigned' AND a.opeTypeId = 'Status' 
GROUP by a.LotID 

注意Having指定组或聚合的搜索条件。 在您的情况下,请将a.NewStatusID ='Assigned' AND a.opeTypeId = 'Status'置于where条件

答案 1 :(得分:0)

select * from 
(   select a.OperationDate,a.LotID,ROW_NUMBER() OVER(partition by a.LotID ORDER BY a.OperationDate desc) as rn
  FROM  [dbo].[MMwLotOperations]   a
  where   a.LotID in ('L705816008','L704511001')
    GROUP by a.LotID,a.OperationDate 
 having  a.NewStatusID ='Assigned' AND a.opeTypeId = 'Status' ) where rn =1

答案 2 :(得分:0)

 select MAX(a.OperationDate) as max_date,a.LotID
  FROM  [dbo].[MMwLotOperations]   a
  where   a.LotID in ('L705816008','L704511001')
    GROUP by a.LotID,a.OperationDate
 having  a.NewStatusID ='Assigned' AND a.opeTypeId = 'Status' 

尝试使用此语句获取最长日期

答案 3 :(得分:0)

使用distinct关键字选择a.LotID

select a.OperationDate,distinct(a.LotID)
FROM  [dbo].[MMwLotOperations]   a
 where   a.LotID in ('L705816008','L704511001')
GROUP by a.LotID,a.OperationDate 
having  a.NewStatusID ='Assigned' AND a.opeTypeId = 'Status' 

我希望这对你有用