SQL 中没有聚合函数的行到列转换

Row to Column transformation without Aggregate function in SQL

伙计们,下面是我的样本table..

当前Table

PropertyAttributeValueID PropertyTypeID PropertyAttributeName PropertyAttributeValue
1000                     3216           Mileage               20.4
1000                     3216           Engine                DIESEL
1000                     3216           Manufacturer          HONDA
1000                     3216           Seat_Capacity         5
1001                     3216           Mileage               19.2
1001                     3216           Engine                PETROL
1001                     3216           Manufacturer          SUZUKI
1001                     3216           Seat_Capacity         4
1002                     3216           Mileage               18.0
1002                     3216           Engine                DIESEL
1002                     3216           Manufacturer          SUZUKI
1002                     3216           Seat_Capacity         4
1003                     3216           Mileage               16.3
1003                     3216           Engine                PETROL
1003                     3216           Manufacturer          HYUNDAI
1003                     3216           Seat_Capacity         5

我需要根据上面的 table 创建这个

想要Table

PropertyAttributeValueID Mileage Engine Manufacturer Seat_Capacity
1000                     20.4    DIESEL HONDA        5
1001                     19.2    PETROL SUZUKI       4
1002                     18.0    DIESEL SUZUKI       4
1003                     16.3    PETROL HYUNDAI      5

我想过使用 pivot,但是如您所见,不需要聚合函数,如何创建它?

您可以使用内部联接

select a.PropertyAttributeValueID 
        , a.PropertyAttributeValue  as Mileage
        , b.PropertyAttributeValue  as Engine
        , c.PropertyAttributeValue  as Manufacturer       
        , d.PropertyAttributeValue  as Seat_Capacity          
from my_table a 
inner join my_table b on a.PropertyAttributeValueID = b.PropertyAttributeValueID 
        and a.PropertyAttributeName='Mileage'
            and b.PropertyAttributeName = 'Engine'
inner join my_table c on a.PropertyAttributeValueID = c.PropertyAttributeValueID 
        and c.PropertyAttributeName='Manufacturer'
inner join my_table d on a.PropertyAttributeValueID = d.PropertyAttributeValueID 
        and d.PropertyAttributeName='Seat_Capacity'

为了获得更好的性能,您可以在 table

上添加复合索引
create index  my_idx on my_table ( PropertyAttributeName
                , PropertyAttributeValueID 
               , PropertyAttributeValue);