1.取時間最新的記錄 不分組有重復(多條CreateTime一樣的都是最新記錄)
select * from test t where pid in ( select PId from Test t where time=(select max(time) from Test t1 where t1.PId=t.PId) group by Pid ) and time=(select max(time) from Test t1 where t1.PId=t.PId)

2.分組后取時間最新的記錄
SELECT max(Id)/*注意Id必須使用聚合函數Max*/ , Pid, MAX(Time) as MaxTime FROM Test GROUP BY pid
3.如果Id是uuid類型無法使用max(id)的解決辦法(使用開窗函數)
select * from ( select row_number() over(partition by [Pid] order by [Time] desc /*降序是為了where KeyId=1 (1是固定值第一條),如果升序由於不知道每組多少條where中KeyId就無法過濾了*/ ) as KeyId,* from Test ) d where KeyId=1
From:https://www.cnblogs.com/xuejianxiyang/p/11980908.html
DROP TABLE IF EXISTS ##tmpTable; --存在表則刪除
select CONVERT(varchar(100), @time, 23) --取datetime的年月日 2019-12-17
select CONVERT(varchar(100), GETDATE(), 24) --取datetime的時間 10:57:47