如何从SQL转移数据

时间:2017-06-16 22:16:22

标签: sql sql-server sql-server-2008

我有以下格式的数据:

enter image description here

我需要以一种方式对其进行格式化,以便为一行中的每个客户端提供地址,开始日期和结束日期。例: enter image description here

提前感谢您的帮助。

1 个答案:

答案 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