Click here to Skip to main content
15,898,755 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello i have three table in my database and i want to select the last record of each user by userid and packID
suppose my three table are as follow table1(UserID, name,contact)
table2(PackID, Packname)
table3(PayID,UserID,PackID)
here i want to retrive the last payID of each user if user has selected the same package two time then i want the record two time for example if table3 value in first row is (1,1,1) and in second row value are (2,1,1) then i want both this two record. but in my query i have group by them with userID that why it will just show the last record how can i get the last record by group them with userID and PackID

please help me

What I have tried:

i have used query is follow
select t1.UserID,t2.payID from table1 as t1
inner join (select max(PayID) as payID,max(UserID) as UserID from table3 group by UserID) as t2
on t1.UserID=t2.userID
Posted
Updated 26-Oct-16 7:45am
Comments
Suvendu Shekhar Giri 26-Oct-16 1:44am    
How to decide that user has selected same pakages 2 times?
Logic not clear. Share some sample input and output in tabular form which may help in understanding your issue.

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
 
Share this answer
 
Try this:
SQL
;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


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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900