根据另一张表中的列值转换一张表中的行

时间:2019-01-25 16:07:25

标签: sql ssms

我在[此处]问了类似的问题:Transposing groups of rows with the same ID into another table 但我不想为每个属性名称写出每一行。我希望能够从TABLE1的一列中获取行(比如说有50个唯一的行),并将它们有效地转置到TABLE2中。

这是一列ATTR_NME(属性名称)表的小示例:

  ID          ATTR_NME          ATTR_VAL
 1000           UPC            00015582981001
 1000          Price              15.99
 1000          Brand               Oreo
 1005           UPC            00038762291010
 1005          Price               12.50
 1005          Brand             Sargento
 1010           UPC            00198872499000
 1010          Price               4.99
 1010          Brand               Olay

因此,ID,UPC,价格和品牌应该是自己的列,以ATTR_VAL作为数据行。这是我的问题与上一个问题的区别:假设我有一个包含50个不同ATTR_NME的表,我想将该数据列与所有这些属性名称一起使用来创建新的转置表,而不必为该表写以下50次不同的属性:

MAX(CASE WHEN ATTR_NME = 'UPC' THEN ATTR_VAL END) AS UPC

我试图为ATTR_NME列中的行声明一个变量,如下所示:

DECLARE @itm varchar(100);
SET @itm = (
      SELECT ATTR_NME
      FROM TABLE1
      );
SELECT ID,
       MAX(CASE WHEN ATTR_NME = @itm THEN ATTR_VAL END) AS [@itm]
FROM TABLE1
GROUP BY ID;

但是,由于多种原因,这没有用;有人希望我在我设置@itm的ATTR_NME周围包装一个聚合函数(但后来我只有一个属性名)。它也没有按我想要的方式标记/命名列。甚至有可能做我想做的事吗?如果是这样,怎么办? TIA。

1 个答案:

答案 0 :(得分:0)

您是在谈论Pivot吗?

如果您需要pivot该表,则无法避免将ATTR_NME放在下面的查询中50次(请参阅评论)

WITH A
AS
(
 SELECT '1000' as ID,          'UPC  ' as ATTR_NME,          '00015582981001' as ATTR_VAL
 UNION ALL SELECT '1000' as ID,          'Price' as ATTR_NME,          '15.99           ' as ATTR_VAL
 UNION ALL SELECT '1000' as ID,          'Brand' as ATTR_NME,          'Oreo            ' as ATTR_VAL
 UNION ALL SELECT '1005' as ID,          'UPC  ' as ATTR_NME,          '00038762291010' as ATTR_VAL
 UNION ALL SELECT '1005' as ID,          'Price' as ATTR_NME,          '12.50           ' as ATTR_VAL
 UNION ALL SELECT '1005' as ID,          'Brand' as ATTR_NME,          'Sargento        ' as ATTR_VAL
 UNION ALL SELECT '1010' as ID,          'UPC  ' as ATTR_NME,          '00198872499000' as ATTR_VAL
 UNION ALL SELECT '1010' as ID,          'Price' as ATTR_NME,          '4.99            ' as ATTR_VAL
 UNION ALL SELECT '1010' as ID,          'Brand' as ATTR_NME,          'Olay            ' as ATTR_VAL
)
SELECT *
FROM A
PIVOT
  (MAX(ATTR_VAL) FOR ATTR_NME in ([Price],[Brand],[UPC]) ) -- here you need to put all the 50 ATTR_NAME
  as PIVOTTABLE