我知道有很多文章向您展示如何PIVOT数据并返回不同的输出,但我真的在努力解决这个问题。我需要将呈现为多行的数据转换为单行。
我的表格包含以下内容
RefNo | Title | FirstName | LastName | DOB | TelNumber | MultipleAcounts
2211700 | Mr | Marshal | Seaton |03/12/1980 | 012365487 | J
2211700 | Mrs | Dallas | Seaton |01/01/1978 | 012345697 | J
将其转换为
RefNo | Title | FirstName | LastName | DOB | TelNumber | MultipleAcounts | J Title | J FirstName | J Surname | J DOB | J TEl | J
2211700 | Mr | Marshal | Seaton |03/12/1980 | 012365487 | J | Mrs | Dallas | Seaton |01/01/1978 | 012345697 | J
我已经完成了几个不同的连接但总是以重复数据结束。
答案 0 :(得分:1)
这是一种方法。这仅在您知道每个RefNo最多只有2行时才有效。
declare @Something table
(
RefNo int
, Title varchar(5)
, FirstName varchar(25)
, LastName varchar(25)
, DOB date
, TelNumber varchar(10)
, MultipleAcounts char(1)
)
insert @Something
select 2211700, 'Mr', 'Marshal', 'Seaton', '03/12/1980', '012365487', 'J' union all
select 2211700, 'Mrs', 'Dallas', 'Seaton', '01/01/1978', '012345697', 'J';
with SortedVals as
(
select *
, ROW_NUMBER() over (partition by RefNo order by Title) as RowNum
from @Something
)
select RefNo
, MAX(case RowNum when 1 then Title end) as Title
, MAX(case RowNum when 1 then FirstName end) as FirstName
, MAX(case RowNum when 1 then DOB end) as DOB
, MAX(case RowNum when 1 then TelNumber end) as TelNumber
, MAX(case RowNum when 1 then MultipleAcounts end) as MultipleAcounts
, MAX(case RowNum when 2 then Title end) as Title2
, MAX(case RowNum when 2 then FirstName end) as FirstName2
, MAX(case RowNum when 2 then DOB end) as DOB2
, MAX(case RowNum when 2 then TelNumber end) as TelNumber2
, MAX(case RowNum when 2 then MultipleAcounts end) as MultipleAcounts2
from SortedVals
group by RefNo
如果你想了解更多关于这种方法的信息,或者如果你需要一个动态版本,这里有两篇关于这种技术的文章。