如何从SQL透视数据

如何从SQL透视数据,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,我有以下格式的数据: 我需要对它进行格式化,以便在一行中为每个客户机获取infor,其中包含地址、开始日期和结束日期。例子: 提前感谢你的帮助 dbfiddle您使用word格式是否意味着数据需要以这种方式进行排列以用于表示,即在数据库之外,还是希望在数据库中以这种方式重新构造数据?如果是后者,为什么需要这样做?你想解决的问题是什么,不能用规范化形式的数据来解决?嗨。到目前为止,您尝试了什么?这是它在输出中的显示方式。我尝试了旋转它,但没有成功,或者操作不正确。数据的图像非常令人沮丧,为什么不

我有以下格式的数据:

我需要对它进行格式化,以便在一行中为每个客户机获取infor,其中包含地址、开始日期和结束日期。例子:

提前感谢你的帮助


dbfiddle

您使用word格式是否意味着数据需要以这种方式进行排列以用于表示,即在数据库之外,还是希望在数据库中以这种方式重新构造数据?如果是后者,为什么需要这样做?你想解决的问题是什么,不能用规范化形式的数据来解决?嗨。到目前为止,您尝试了什么?这是它在输出中的显示方式。我尝试了旋转它,但没有成功,或者操作不正确。数据的图像非常令人沮丧,为什么不直接复制/粘贴为文本?谢谢您的回复。唯一的问题是,对于某些记录,它不是3个开始日期和结束日期值,但可能更多甚至更少,例如只有1个开始日期和结束日期或4个值。是否有任何方法可以动态地获取这些记录?要获得无限的可变性,您需要更复杂的代码。被称为动态sql并不是不可能的,只是更难。但如果您想在这个广泛的非规范化表示中满足地址的需求,建议您选择一个最大数量。
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.