문제

I have a table like below which would have the product description

╔════╦══════════════╦══════╗
║ Id ║  name        ║ price║
╠════╬══════════════╬══════╣
║  1 ║ Apple        ║ 23   ║
║  2 ║ shirt        ║  148 ║
║  3 ║ computer     ║  101 ║
║  4 ║ printer      ║  959 ║
╚════╩══════════════╩══════╝

and another table which is holding the attributes like linked by the ID

╔════╦══════════════╦══════╗
║ Id ║  attr_name   ║ Value║
╠════╬══════════════╬══════╣
║  1 ║ color        ║ red  ║
║  1 ║ size         ║  xl  ║
║  1 ║ brand        ║  App ║
║  2 ║ color        ║  blue║
║  2 ║ size         ║  l   ║
║  3 ║ color        ║  blue║
║  3 ║ size         ║  xxl ║
║  3 ║ brand        ║  HP  ║
╚════╩══════════════╩══════╝

Is there any possible way to bring a table like below if I know the attribute name is going to be only color size and brand

╔════╦══════════╦═══════╦═══════╦══════╦══╗
║ id ║   name   ║ color ║ brand ║ size ║  ║
╠════╬══════════╬═══════╬═══════╬══════╬══╣
║  1 ║ apple    ║ red   ║ app   ║ xl   ║  ║
║  2 ║ shirt    ║ blue  ║       ║ l    ║  ║
║  3 ║ computer ║ blue  ║ HP    ║ XXL  ║  ║
║  4 ║ printer  ║       ║       ║      ║  ║
╚════╩══════════╩═══════╩═══════╩══════╩══╝

도움이 되었습니까?

해결책

You should be able to use an aggregate function with a CASE expression to convert the rows into columns:

select d.id,
  d.name,
  max(case when a.attr_name = 'color' then a.value end) color,
  max(case when a.attr_name = 'brand' then a.value end) brand,
  max(case when a.attr_name = 'size' then a.value end) size
from product_description d
inner join product_attributes a
  on d.id = a.id
group by d.id, d.name;

See SQL Fiddle with Demo.

Since you are using Oracle 11g, then you can use the PIVOT function to get the result:

select id, name, Color, Brand, "Size"
from
(
  select d.id, d.name,
    a.attr_name, a.value
  from product_description d
  inner join product_attributes a
    on d.id = a.id
) src
pivot
(
  max(value)
  for attr_name in ('color' as Color,
                    'brand' as Brand,
                    'size' as "Size")
) p;

See SQL Fiddle with Demo

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top