这个问题在这里已有答案:
我有桌子跟着
ID Cust_ID Amount
1 1 10
2 1 20
3 2 30
4 2 40
5 3 50
我需要最新的Cust_Id结果记录,如下所示
ID Cust_Id Amount
2 1 20
4 2 40
5 3 50
我像这样尝试了查询
Select Top 1 *Id,Cust_Id,Amount from tablename
Group by Cust_Id
Order by Id desc
你可以尝试使用row_number()
select * from
(
select *,row_number() over(partition by cust_id order id desc) rn from tablename
)A where rn=1
使用row_number()
select * from
(
select *,
row_number() over(partition by cust_id order by Amount desc) rn
from tabl
) t where rn=1
或使用相关子查询
select t1.* from table t1
where t1.Amount= (select max(Amount) from table t2
where t1.cust_id=t2.cust_id)
你也可以尝试以下
select id,cust_id,amount
from YourTable t1
where id =(select max(t2.id) from YourTable t2 where t2.Cust_ID=t1.Cust_ID)
order by id