【问题标题】:How to pivot Feature Value Based On Features Exist on table Input Data?如何根据表输入数据上存在的特征来透视特征值?
【发布时间】:2021-03-28 14:08:13
【问题描述】:

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

我需要将特征显示为表输入数据中存在 C 部分和 X 部分的枢轴。

我需要在一行中水平显示 Part C AND Part X AND feature for Part C AND feature For Part X。

当对每个特征进行透视特征值时,我依赖于具有特征名称的表格部件数据

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

零件数据表代表我将从它中透视数据的事务表。

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

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

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   

【问题讨论】:

    标签: sql tsql sql-server-2012 pivot


    【解决方案1】:

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

    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

    零件 |部分 |当前_c |当前_x |电压_c |电压_x |电阻器_c |电阻器_x ----: | ----: | :-------- | :-------- | :-------- | :-------- | :--------- | :--------- 1290 | 1590 | 40V | 30V | 50k | 70k | 90A | 20A

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-21
      • 1970-01-01
      • 1970-01-01
      • 2021-11-07
      • 2020-09-25
      • 2015-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多