Here is my SQL Server table:
DECLARE @EMP TABLE
(
Id INT,
NAME VARCHAR(200),
AlarmOnTimeStamp DATETIMEOFFSET,
AlarmOffTimeStamp DATETIMEOFFSET NULL
);
DECLARE @EMPCOMMENT TABLE
(
EmpId INT,
Comment VARCHAR(2000)
)
INSERT INTO @EMP VALUES (1121, 'Test1', '2020-04-09 01:56:29.507', NULL)
INSERT INTO @EMP VALUES (57, 'Test1', '2020-04-09 02:56:29.507', NULL)
INSERT INTO @EMP VALUES (992, 'Test2', '2020-04-09 01:56:29.507', '2020-04-09 03:56:29.507')
INSERT INTO @EMPCOMMENT VALUES (2, 'Test1')
INSERT INTO @EMPCOMMENT VALUES (2, 'Test2')
SELECT *
FROM @emp e
LEFT JOIN @EMPCOMMENT ec ON ec.Id = e.Id
SELECT
*,
rn = ROW_NUMBER() OVER (PARTITION BY e.Name ORDER BY AlarmOnTimeStamp, e.Name DESC)
FROM @emp e
LEFT JOIN @EMPCOMMENT ec ON e.Id = ec.EmpId
Output:
Id Name AlarmOnTimeStamp AlarmOffTimeStamp EmpId Comment rn
--------------------------------------------------------------------------------------------
2 Test1 2020-04-09 02:56:29 NULL 2 Good 1
2 Test1 2020-04-09 02:56:29 NULL 2 Best 1
3 Test2 2020-04-09 01:56:29 2020-04-09 03:56:29.50 NULL NULL 1
I just want the above result
If you see in the screenshot the 1st record show be removed, reason as it an old record, I just wanted if employee name are same, get its latest record with all its comment
I think that you want:
SELECT *
FROM (
SELECT *, RANK() OVER(PARTITION BY e.Name ORDER BY e.AlarmOnTimeStamp desc) rn
FROM @emp e
LEFT JOIN @EMPCOMMENT ec ON ec.EmpId = e.Id
) t
WHERE rn = 1
This ranks rows having the same employee name by descending id, and keep the top rows only (ties included).
For your sample data, the query yields :
Id | NAME | AlarmOnTimeStamp | AlarmOffTimeStamp | EmpId | Comment | rn -: | :---- | :-------------------------- | :-------------------------- | ----: | :------ | :- 2 | Test1 | 2020-04-09 02:56:29.5070000 | null | 2 | Test1 | 1 2 | Test1 | 2020-04-09 02:56:29.5070000 | null | 2 | Test2 | 1 3 | Test2 | 2020-04-09 01:56:29.5070000 | 2020-04-09 03:56:29.5070000 | null | null | 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.