答案 0 :(得分:0)
CREATE TABLE client_address ([id] int, [clientid] int, [Address] varchar(3), [StartDate] date, [EndDate] datetime) ; INSERT INTO client_address ([id], [clientid], [Address], [StartDate], [EndDate]) VALUES (1, 123, 'sdf', '2015-03-17', '2015-12-23'), (2, 123, 'pqr', '2015-12-23', '2016-10-23'), (3, 123, 'abc', '2016-10-23', NULL) ; select clientid , max(case when rn=3 then address end) address1 , max(case when rn=3 then StartDate end) StartDate1 , max(case when rn=3 then EndDate end) EndDate1 , max(case when rn=2 then address end) address2 , max(case when rn=2 then StartDate end) StartDate2 , max(case when rn=2 then EndDate end) EndDate2 , max(case when rn=1 then address end) address3 , max(case when rn=1 then StartDate end) StartDate3 , max(case when rn=1 then EndDate end) EndDate3 from ( select * , row_number() over(partition by clientid order by coalesce(EndDate,getdate()) DESC) as rn from client_address ) ca where rn < 4 group by clientid ; GO
clientid | address1 | StartDate1 | EndDate1 | address2 | StartDate2 | EndDate2 | address3 | StartDate3 | EndDate3 -------: | :------- | :------------------ | :------------------ | :------- | :------------------ | :------------------ | :------- | :------------------ | :------- 123 | sdf | 17/03/2015 00:00:00 | 23/12/2015 00:00:00 | pqr | 23/12/2015 00:00:00 | 23/10/2016 00:00:00 | abc | 23/10/2016 00:00:00 | null Warning: Null value is eliminated by an aggregate or other SET operation.
dbfiddle here