试图让PIVOT工作

时间:2016-12-08 22:31:13

标签: sql-server

我正在尝试使用数据透视表。基于我在网上找到的例子,我有这个:

 select *
from (
 select CapVehicles.Cvehicle_DerText
  , NVDDictionaryOption.DO_Description as OptionText
  , [V12 2dr Touchtronic Auto]
  , [V12 Launch Edition 2dr Touchtronic Auto]
  , 1 as c
 from NVDStandardEquipment
 left join NVDDictionaryOption on NVDStandardEquipment.SE_OptionCode = NVDDictionaryOption.DO_OptionCode
 left join NVDDictionaryCategory on NVDDictionaryOption.DO_CatCode = NVDDictionaryCategory.DC_CatCode
 left join CapVehicles on NVDStandardEquipment.SE_Id = CapVehicles.CVehicle_Id
 where NVDStandardEquipment.SE_Id in (
   select distinct CVehicle_Id
   from CapVehicles
   left join CapDer on CapVehicles.CVehicle_Id = CapDer.CDer_Id
   where CapDer.cder_discontinued is null 
     and capvehicles.cvehicle_mantext = 'ASTON MARTIN' 
     and capvehicles.cvehicle_shortmodtext = 'DB11'
   ) and NVDStandardEquipment.SE_EffectiveTo is null
 ) as s
pivot (max(c) for Cvehicle_DerText in 
  ([V12 2dr Touchtronic Auto], [V12 Launch Edition 2dr Touchtronic Auto])) as pvt

我的原始数据看起来像这样,基本上我试图在网格中显示哪些车辆有哪些选项,选项为行,车辆为列。

V12 2dr Touchtronic Auto | Adaptive damping system
V12 2dr Touchtronic Auto | Cruise control  
V12 Launch Edition 2dr Touchtronic Auto | Adaptive damping system
V12 Launch Edition 2dr Touchtronic Auto | Cruise control 

上面有很多错误:

  

无效的列名称'V12 2dr Touchtronic Auto'   列名称无效'V12 Launch Edition 2dr Touchtronic Auto'。
  PIVOT运算符中指定的列名“V12 2dr Touchtronic Auto”与PIVOT参数中的现有列名冲突。
  PIVOT运算符中指定的列名“V12 Launch Edition 2dr Touchtronic Auto”与PIVOT参数中的现有列名冲突。   'pvt'多次指定“V12 2dr Touchtronic Auto”列。

1 个答案:

答案 0 :(得分:0)

我认为'V12 2dr Touchtronic Auto','V12 Launch Edition 2dr Touchtronic Auto'是一个值,而不是列名。 你应该从内部选择中删除它。

试试这个:

select *
from (
 select CapVehicles.Cvehicle_DerText
  , NVDDictionaryOption.DO_Description as OptionText
  , 1 as c
 from NVDStandardEquipment
 left join NVDDictionaryOption on NVDStandardEquipment.SE_OptionCode = NVDDictionaryOption.DO_OptionCode
 left join NVDDictionaryCategory on NVDDictionaryOption.DO_CatCode = NVDDictionaryCategory.DC_CatCode
 left join CapVehicles on NVDStandardEquipment.SE_Id = CapVehicles.CVehicle_Id
 where NVDStandardEquipment.SE_Id in (
   select distinct CVehicle_Id
   from CapVehicles
   left join CapDer on CapVehicles.CVehicle_Id = CapDer.CDer_Id
   where CapDer.cder_discontinued is null 
     and capvehicles.cvehicle_mantext = 'ASTON MARTIN' 
     and capvehicles.cvehicle_shortmodtext = 'DB11'
   ) and NVDStandardEquipment.SE_EffectiveTo is null
 ) as s
pivot (max(c) for Cvehicle_DerText in 
  ([V12 2dr Touchtronic Auto], [V12 Launch Edition 2dr Touchtronic Auto])) as pvt