sql中无聚合函数的行到列转换

5fjcxozz  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(465)

各位,下面是我的样品表。。
当前表格

  1. PropertyAttributeValueID PropertyTypeID PropertyAttributeName PropertyAttributeValue
  2. 1000 3216 Mileage 20.4
  3. 1000 3216 Engine DIESEL
  4. 1000 3216 Manufacturer HONDA
  5. 1000 3216 Seat_Capacity 5
  6. 1001 3216 Mileage 19.2
  7. 1001 3216 Engine PETROL
  8. 1001 3216 Manufacturer SUZUKI
  9. 1001 3216 Seat_Capacity 4
  10. 1002 3216 Mileage 18.0
  11. 1002 3216 Engine DIESEL
  12. 1002 3216 Manufacturer SUZUKI
  13. 1002 3216 Seat_Capacity 4
  14. 1003 3216 Mileage 16.3
  15. 1003 3216 Engine PETROL
  16. 1003 3216 Manufacturer HYUNDAI
  17. 1003 3216 Seat_Capacity 5

我需要从上面的表创建这个表
所需表格

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

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

fumotvh3

fumotvh31#

你可以使用内部连接

  1. select a.PropertyAttributeValueID
  2. , a.PropertyAttributeValue as Mileage
  3. , b.PropertyAttributeValue as Engine
  4. , c.PropertyAttributeValue as Manufacturer
  5. , d.PropertyAttributeValue as Seat_Capacity
  6. from my_table a
  7. inner join my_table b on a.PropertyAttributeValueID = b.PropertyAttributeValueID
  8. and a.PropertyAttributeName='Mileage'
  9. and b.PropertyAttributeName = 'Engine'
  10. inner join my_table c on a.PropertyAttributeValueID = c.PropertyAttributeValueID
  11. and c.PropertyAttributeName='Manufacturer'
  12. inner join my_table d on a.PropertyAttributeValueID = d.PropertyAttributeValueID
  13. and d.PropertyAttributeName='Seat_Capacity'

为了获得更好的性能,可以在表上添加一个复合索引

  1. create index my_idx on my_table ( PropertyAttributeName
  2. , PropertyAttributeValueID
  3. , PropertyAttributeValue);
展开查看全部

相关问题