Всегда легче ответить, если вы можете дать определение схемы и некоторые примеры данных и ожидаемый результат, а не комментарий. Я попытался определить схему, у меня нет примеров данных и думаю , что этот ответ дает то, что вы хотите:
/*create table Clothing (
EmployeeID int not null,
CostCentre varchar(10) not null,
AssociateLevel int not null,
IssueDate datetime not null,
TrouserSize int null,
TrouserLength int null,
TopSize varchar(4) null,
ShoeSize varchar(10) null
)*/
go
with Trousers as (
select
EmployeeID,
CostCentre,
AssociateLevel,
IssueDate,
TrouserSize,
TrouserLength,
RANK() OVER (PARTITION BY EmployeeID ORDER BY IssueDate Desc) as RowNum
from
Clothing
where
TrouserSize is not null
), Tops as (
select
EmployeeID,
CostCentre,
AssociateLevel,
IssueDate,
TopSize,
RANK() OVER (PARTITION BY EmployeeID ORDER BY IssueDate Desc) as RowNum
from
Clothing
where
TopSize is not null
), Shoes as (
select
EmployeeID,
CostCentre,
AssociateLevel,
IssueDate,
ShoeSize,
RANK() OVER (PARTITION BY EmployeeID ORDER BY IssueDate Desc) as RowNum
from
Clothing
where
ShoeSize is not null
)
select
COALESCE(tr.EmployeeID,tops.EmployeeID,sh.EmployeeID) as EmployeeID,
tr.CostCentre,
tr.AssociateLevel,
tr.IssueDate,
tr.TrouserSize,
tr.TrouserLength,
tops.CostCentre,
tops.AssociateLevel,
tops.IssueDate,
tops.TopSize,
sh.CostCentre,
sh.AssociateLevel,
sh.IssueDate,
sh.ShoeSize
from
Trousers tr
full outer join
Tops
on
tr.EmployeeID = Tops.EmployeeID
full outer join
Shoes sh
on
tr.EmployeeID = sh.EmployeeID and
Tops.EmployeeID = sh.EmployeeID
where
(tr.RowNum is null or tr.RowNUm = 1) and
(Tops.RowNum is null or Tops.RowNUm = 1) and
(sh.RowNum is null or sh.RowNum = 1)