Below output:
Reg_id class_id reg_date
2011213807261 0000111016294 2019-02-14 12:22:24.057
2011213807254 0000111016294 2019-02-14 12:22:24.057
2011214239559 0000111016447 2019-09-21 03:55:25.357
2011214239573 0000111016447 2019-09-21 03:55:25.357
4511999718167 0000111016455 2017-07-23 10:39:36.043
4511999718235 0000111016455 2017-07-23 10:39:36.043
4511999717931 0000111016456 2017-03-17 12:35:32.537
4511999717924 0000111016456 2017-03-17 12:35:32.537
Above output I have same class id of two records. I want 2nd row of same class id as 1st row put in same id of 1st row.
Needed output
Reg_id class_id reg_date Reg_id class_id reg_date
2011213807261 0000111016294 2019-02-14 12:22:24.057 2011213807254 0000111016294 2019-02-14 12:22:24.057
2011214239559 0000111016447 2019-09-21 03:55:25.357 2011214239573 0000111016447 2019-09-21 03:55:25.357
4511999718167 0000111016455 2017-07-23 10:39:36.043 4511999718235 0000111016455 2017-07-23 10:39:36.043
4511999717931 0000111016456 2017-03-17 12:35:32.537 4511999717924 0000111016456 2017-03-17 12:35:32.537
I need output like above, same id records should display in front of same id of 1st record row.
You can achieve this using ROW_NUMBER()
function as given below:
declare @TABLE Table(reg_id varchar(20), class_id varchar(20), regdate datetime)
insert into @table values
('2011213807261','0000111016294','2019-02-14T12:22:24.057')
,('2011213807254','0000111016294','2019-02-14T12:22:24.057');
WITH CTE_TableRank AS
(
SELECT *,ROW_NUMBER() OVER (PARTITION BY class_id ORDER BY reg_id) as rnk
FROM @table
)
SELECT c1.reg_id, c1.class_id, c1.regdate, c2.reg_id, c2.class_id, c2.regdate
FROM CTE_TableRank AS c1
INNER JOIN CTE_TableRank AS c2 ON c1.class_id = c1.class_id
WHERE c1.rnk = 1 AND c2.rnk = 2
reg_id | class_id | regdate | reg_id | class_id | regdate |
---|---|---|---|---|---|
2011213807254 | 0000111016294 | 2019-02-14 12:22:24.057 | 2011213807261 | 0000111016294 | 2019-02-14 12:22:24.057 |
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.