将列值转换为列

时间:2019-07-18 18:41:36

标签: sql

当前数据库如下:

Current data structure

我正尝试将其转换如下:

Expected data structure

我想出的最好方法是SQL枢纽。但这会将产品ID分组,并且仅给出我们在上面看到的330个三行之一。我无法想到任何其他方法来解决此问题。如果有人能想出任何解决办法,请您分享您的想法?

2 个答案:

答案 0 :(得分:0)

您可以使用条件聚合:

select productid,
       max(case when description = 'Part No' then unitdesc end) as partno,
       . . .  -- and so on for the other columns
from t
group by productid;

编辑:

我知道,每个产品有多行。您有一个问题,因为SQL表表示无序集。没有排序,除非您有指定排序的列。那不是很明显。

因此,以下内容将创建单个行,但不一定会按您的意愿进行组合:

select productid,
       max(case when description = 'Part No' then unitdesc end) as partno,
       . . .  -- and so on for the other columns
from (select t.*, row_number() over (partition by productid, description order by productid) as seqnum
      from t
     ) t
group by productid, seqnum;

如果您的某一列确实捕获了行的顺序,请在order by中使用该列。

答案 1 :(得分:0)

您可以使用LEFT JOIN来检索相应的值:

select
  p.product_id,
  n.unit_desc as part_no,
  d.unit_desc as description,
  pn.unit_desc as price_now,
  u.unit_desc as unit
from (select distinct product_id from t) p
left join (select product_id, description from t where description = 'Part No') n
left join (select product_id, description from t where description = 'Description') d
left join (select product_id, description from t where description = 'Price Now') pn
left join (select product_id, description from t where description = 'Unit') u