This question already has an answer here:
I need to select last records from my table using group by UserID
I need to select StartDate,EndDate from last records grouping by userID
I am using code below
select StartDate,EndDate from usersworktime group by userid,StartDate,EndDate
The problem is that i am getting all rows instead only the last two of my table
Assuming that the start and end dates will always be the highest values then you need to drop some of the columns from the GROUP BY (having all the columns in the GROUP BY is kinda like using DISTINCT) and use an aggregate function on the other column:
SELECT UserId,
MAX(StartDate) AS StartDate,
MAX(EndDate) AS EndDate
FROM usersworktime
GROUP BY UserId;
Otherwise, if that isn't the case, you can use a CTE and ROW_NUMBER:
WITH CTE AS(
SELECT UserID,
StartDate,
EndDate,
ROW_NUMBER() OVER (PARTITION BY UserID ORDER BY UsersWordTimeID DESC) AS RN
FROM usersworktime)
SELECT UserID,
StartDate,
EndDate
FROM CTE
WHERE RN = 1;
I think i found a solution
SELECT usersworktimeid, userid,StartDate, EndDate
FROM usersworktime
WHERE usersworktimeid IN (
SELECT MAX(usersworktimeid)
FROM usersworktime
GROUP BY UserID
);
来源:https://stackoverflow.com/questions/54542685/select-last-records-from-table-using-group-by
