且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在SQL中选择每个用户的最后一条记录

更新时间:2023-01-28 19:34:45

你好

如果你是使用sql查询,你可以

1)OredrByAsc(* fieldName),显示最后一条记录,冷杉

2)选择top(1)选择第一条记录,最后一个



如果您使用的是Entity Framework:

您可以使用.LastOrDefault();检索最后一个



希望它有效
hello
if you are using sql query, you can
1) OredrByAsc(* fieldName), to show the last record, firs
2) Select top(1) to select the firs record, infact the last one

if you are using Entity Framework:
you can use .LastOrDefault(); to retrieve last one

hope it works


试试这个:

Try this:
;WITH cte1
AS (
	SELECT PAYID
		,USERID
		,PACKID
		,RANK() OVER (
			PARTITION BY USERID ORDER BY PAYID DESC
			) AS Rnk
	FROM table3
	)
	,cte2
AS (
	SELECT PAYID
		,USERID
		,PACKID
	FROM cte1
	WHERE Rnk = 1
	)
	
	SELECT t3.PAYID
		,t3.USERID
		,t3.PACKID
	FROM table3 t3
	INNER JOIN cte2 ON t3.PAYID <= cte2.PAYID
		AND t3.USERID = cte2.USERID
		AND t3.PACKID = cte2.PACKID





我做了一些假设:

1. PAYID会增加随着越来越多的记录被添加。换句话说,PAYID越大,它越近。你对MAX(PAYID)的使用似乎表明我的假设是正确的。

2.如果那些重复与USERID相对应,你需要重复一次USERID,PACKID组合,PACKID组合对应于最新的PAYID那个用户。因此,重复可能超过2次。您将在我的查询中获得所有重复。



I made some assumptions:
1. PAYID will increase as more and more records get added. In other words, the greater the PAYID, the more recent it is. Your usage of MAX(PAYID) seems to suggest my assumption is correct.
2. You need all repetitions of a USERID, PACKID combo if those repetitions match the USERID, PACKID combo corresponding to the latest PAYID for that USER. So, there might be more than 2 repetitions. You will get all repetitions in my query.