MSSQL - 如何根据max id选择多个列

时间:2018-03-28 07:17:05

标签: sql sql-server tsql

enter image description here

结果必须是针对不同的car_id,我想选择max(exActId)。必须根据driver_idcontract_id选择max(exActId)carId

结果必须像

enter image description here

我怎样才能做到这一点?

4 个答案:

答案 0 :(得分:4)

您可以使用row_number()执行此操作,但使用相关子查询通常更有效:

select t.*
from t
where t.exActId = (select max(t2.exActId) from t t2 where t2.carId = t.carId);

答案 1 :(得分:1)

根据Max(ID)使用分组依据 例如:

Select max(ID),name from TableName group BY ID

答案 2 :(得分:1)

试试这个:

SELECT *
FROM YourTable
WHERE exActId IN (select MAX(exActId) from YourTable GROUP BY CarID);

答案 3 :(得分:1)

  SELECT CAR_ID,DRIVER_ID,exActId,contract_id FROM 
    (
      SELECT CAR_ID,DRIVER_ID,exActId,contract_id,ROW_NUMBER() OVER(PARTITION BY  CAR_ID,exActId ORDER BY exActId DESC) AS ro_NO FROM TABLE
    ) 
  WHERE  ro_NO =1