Select last records from table using group by [duplicate]

◇◆丶佛笑我妖孽 提交于 2019-11-28 14:50:56

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
);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!