使用一列创建另一列

时间:2019-07-17 19:43:40

标签: sql

我有这张桌子:

PRODUCTNUMBER   AttributeTypeName               TextValue
1020M              Core Style                    Fashion
1020M               Length/Weight                 LONG
1020M              Quilted/NonQuilted             NonQuilted

我想创建一个查询给我这张表

 AttributeTypeName = Core Style --> TextValue  Stylecode
 AttributeTypeName =Quilted/NonQuilted  --> TextValue  FabricCategory
 AttributeTypeName =Length/Weight  --> TextValue  LableCode

我正在使用保护套,但是每件物品我要得到3行,我只想看到这样的一行

PRODUCTNUMBER   Stylecode    FabricCategory      LableCode

1020M             Fashion       NonQuilted       LableCode

3 个答案:

答案 0 :(得分:0)

只需全部使用uniona

    select 'AttributeTypeName=',
    max(case when AttributeTypeName='Core Style'
    then  TextValue end) from table
   union all
    select 'AttributeTypeName=',
    max(case when AttributeTypeName='Quilted/NonQuilted'
    then  TextValue end) from table
     union all
    select 'AttributeTypeName=',
    max(case when AttributeTypeName='Length/Weight'
    then  TextValue end) from table

答案 1 :(得分:0)

您可以尝试在同一张表上加入

const checkRequiredProps = <I, P extends keyof I>(instance: I, requiredProps: P[]) => {
    const props = requiredProps.filter((prop) => {
      return !instance[prop];
    });

    console.log(props);
};

interface IHuman {
    name: string;
    age: number;
}

interface IWerewolf {
    name: string;
}

class Test {
    private readonly _name: string;

    constructor(human: IHuman = {} as IHuman, werewolf: IWerewolf = {} as IHuman) {
        checkRequiredProps(human, ['name', 'age']);
        checkRequiredProps(werewolf, ['name']);
        this._name = human.name;
    }

    public get name(): string {
        return this._name;
    }
}

const test = new Test({ name: 'loki', age: 10 }, { name: 'wolfington' });

以及第一个属性是否缺失

select  a.PRODUCTNUMBER
 , a.TextValue StyleCode 
 , b.TetValue FabricCategory
 , c.TextValue  LabelCode 
from my_table a 
left join my_table b on a.productnumber  = b.productnumber 
    and b.AttributeTypeName ='Quilted/NonQuilted'
left join my_table c on a.productnumber  = c.productnumber 
    and c.AttributeTypeName ='Length/Weight'
where a.AttributeTypeName ='Core Style'

答案 2 :(得分:0)

这将适用于大多数数据库,如果您的列表仅是这三列

SELECT PRODUCT_NUMBER,
       MAX(CASE WHEN AttributeTypeName = 'Core Style' THEN TextValue ELSE NULL END) AS StyleCode,
       MAX(CASE WHEN AttributeTypeName = 'Length/Weight' THEN TextValue ELSE NULL END) AS FabricCategory,
       MAX(CASE WHEN AttributeTypeName = 'Quilted/NonQuilted' THEN TextValue ELSE NULL END) AS LableCode,      
  FROM TEST_DATA
 GROUP
    BY PRODUCT_NUMBER;