O ile nie brakuje mi czegoś w twoim wyjaśnieniu, nie potrzebujesz AttributeMask
. Jeśli końcowe nazwy kolumn będą po prostu oryginalnymi nazwami kolumn, a następnie Kind
wartości, możesz użyć:
select *
from
(
select LotId,
SomeText,
col+'_'+Kind col,
value
from
(
select l.LotId,
l.SomeText,
cast(a.AttributeId as varchar(8)) attributeid,
cast(a.LotId as varchar(8)) a_LotId,
a.Val,
a.Kind
from @Lot l
left join @Attribute a
on l.LotId = a.LotId
) src
cross apply
(
values ('attributeid', attributeid),('LotId', a_LotId), ('Value', Val), ('Kind', Kind)
) c (col, value)
) d
pivot
(
max(value)
for col in (attributeid_Kind1, LotId_Kind1, Value_Kind1, Kind_Kind1,
attributeid_Kind2, LotId_Kind2, Value_Kind2, Kind_Kind2,
attributeid_Kind3, LotId_Kind3, Value_Kind3, Kind_Kind3)
) piv;
Zobacz SQL Fiddle z wersją demonstracyjną . Daje to wynik:
| LOTID | SOMETEXT | ATTRIBUTEID_KIND1 | LOTID_KIND1 | VALUE_KIND1 | KIND_KIND1 | ATTRIBUTEID_KIND2 | LOTID_KIND2 | VALUE_KIND2 | KIND_KIND2 | ATTRIBUTEID_KIND3 | LOTID_KIND3 | VALUE_KIND3 | KIND_KIND3 |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| 1 | WithAll | 1 | 1 | Foo1 | Kind1 | 2 | 1 | Foo2 | Kind2 | 3 | 1 | Foo3 | Kind3 |
| 2 | Hello | (null) | (null) | (null) | (null) | 10 | 2 | Bar2 | Kind2 | (null) | (null) | (null) | (null) |
| 3 | World | (null) | (null) | (null) | (null) | (null) | (null) | (null) | (null) | 12 | 3 | Bar3 | Kind3 |