How do I get the min timestamp value of the same Id number with its corresponding Value using SQL?
Would anybody help me with this problem? (Please see attached image below)
Sample Table
Sample Table of what should be the result
How do I get the min timestamp value of the same Id number with its corresponding Value using SQL?
Would anybody help me with this problem? (Please see attached image below)
Sample Table
Sample Table of what should be the result
Filter the data based on RANK (Transact-SQL):
declare @temp as table
(
employeeCode varchar(11) not null,
TimeStamps datetime not null,
Value varchar(9) not null
);
insert into @temp
(employeeCode, TimeStamps, Value)
values
('A021','2015/08/25 11:39:02.937','3000'),
('A021','2015/08/25 11:39:02.937','Monthly'),
('A021','2015/09/02 13:18:42.630','3200'),
('A021','2015/09/02 13:18:42.630','Monthly'),
('ACK00005','2015/06/09 15:15:45.970','12000'),
('ACK00005','2015/06/09 15:15:45.970','Monthly'),
('ACK00005','2015/06/09 16:17:37.420','15000'),
('ACK00005','2015/06/09 16:17:37.420','Monthly'),
('PA001','2015/06/09 15:15:45.970','10000'),
('PA001','2015/06/09 15:15:45.970','Monthly'),
('PA001','2015/06/09 16:17:37.420','12000'),
('PA001','2015/06/09 16:17:37.420','Monthly'),
('PAPH0001','2015/06/09 15:15:45.970','5000'),
('PAPH0001','2015/06/09 15:15:45.970','Monthly'),
('PAPH0001','2015/06/09 16:17:37.420','8000'),
('PAPH0001','2015/06/09 16:17:37.420','Monthly'),
('PAPH0002','2015/06/11 17:05:41.720','5000'),
('PAPH0002','2015/06/11 17:05:41.720','Monthly');
The solution involves ranking the rows in the desired Timestamps order, giving ties the same rank, and restarting the numbering when the employeeCode changes. We return rows that rank #1:
WITH CTE AS
(
SELECT *,
rnk = RANK() OVER (
PARTITION BY T.employeeCode
ORDER BY T.TimeStamps)
FROM @temp AS T
)
SELECT
CTE.employeeCode,
CTE.TimeStamps,
CTE.Value
FROM CTE
WHERE CTE.rnk = 1;
Output:
For more general 'n' rows per group problems, please see: