如何根据 table 输入数据中存在的特征来转换特征值?

How to pivot Feature Value Based On Features Exist on table Input Data?

我在 SQL Server 2012 上工作。我有一个问题:我无法为 table 输入数据中存在的每个部分旋转特征。

我需要将特征显示为枢轴,其中部分 C 和部分 x 存在于 table 输入数据中。

我需要在一行中水平显示 C 部分和 X 部分以及 C 部分的特征和 X 部分的特征。

当每个特征的枢轴特征值时,我依赖 table 具有特征名称的零件数据

以及 table 输入数据中存在的部分的特征值。

部分数据 table 表示交易 table,我将从中获取数据。

当显示基于table特征排列时,我使用显示顺序来排列特征。

我根据 table 输入数据中存在的 C 部分和 X 部分的每个特征透视数据(搜索 table)

CREATE TABLE #InputData
(
    PartC INT,
    PartX  int
)

INSERT INTO #InputData (PartC, PartX)
VALUES (1290, 1590)

CREATE TABLE #features
(
    FeatureId  int,
    FeatureName nvarchar(50),
    DisplayOrder  int
)

INSERT INTO #features (FeatureId, FeatureName, DisplayOrder)
VALUES (124003, 'Current', 1),
       (157301, 'Voltage', 2),
       (980012, 'Resistor', 3)

CREATE TABLE #partsdata
(
    PartId  int,
    FeatureId int,
    FeatureValue nvarchar(20)
)

INSERT INTO #partsdata (PartId, FeatureId, FeatureValue)
VALUES (1290, 124003, '40V'),
       (1290, 157301, '50k'),
       (1290, 980012, '90A'),
       (1590, 124003, '30V'),
       (1590, 157301, '70k'),
       (1590, 980012, '20A')
 
   

结果:

 Partc Partx  Current-C Current-X Volt-C Volt-X Resistor-C Resistor-X   
 1290  1590     40V        30V      50k   70k       90A      20A   

您可以像这样进行条件聚合:

select d.partc, d.partx,
    max(case when p.partid = d.partc and f.featurename = 'Current' then featurevalue end) as current_c,
    max(case when p.partid = d.partx and f.featurename = 'Current' then featurevalue end) as current_x,
    max(case when p.partid = d.partc and f.featurename = 'Voltage' then featurevalue end) as voltage_c,
    max(case when p.partid = d.partx and f.featurename = 'Voltage' then featurevalue end) as voltage_x,
    max(case when p.partid = d.partc and f.featurename = 'Resistor' then featurevalue end) as resistor_c,
    max(case when p.partid = d.partx and f.featurename = 'Resistor' then featurevalue end) as resistor_x        
from #partsdata p
inner join #features f on f.featureid = p.featureid
inner join #inputdata d on p.partid in (d.partc, d.partx)
group by d.partc, d.partx

Demo on DB Fiddle:

partc | partx | current_c | current_x | voltage_c | voltage_x | resistor_c | resistor_x
----: | ----: | :-------- | :-------- | :-------- | :-------- | :--------- | :---------
 1290 |  1590 | 40V       | 30V       | 50k       | 70k       | 90A        | 20A