Attach / Remove Items with EAV Table

I have a table like below that will have a product description

╔════╦══════════════╦═════╗
β•‘ Id β•‘ name β•‘ priceβ•‘
╠════╬══════════════╬═════╣
β•‘ 1 β•‘ Apple β•‘ 23 β•‘
β•‘ 2 β•‘ shirt β•‘ 148 β•‘
β•‘ 3 β•‘ computer β•‘ 101 β•‘
β•‘ 4 β•‘ printer β•‘ 959 β•‘
β•šβ•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•

and another table that stores the attributes associated with the identifier

╔════╦══════════════╦═════╗
β•‘ 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 the table as shown below if I know that the attribute name will only be color size and brand

╔════╦══════════╦════════════════╦═══════╗
β•‘ id β•‘ name β•‘ color β•‘ brand β•‘ size β•‘ β•‘
╠════╬══════════╬═══════╬═══════╬══════╬══╣
β•‘ 1 β•‘  β•‘  β•‘  β•‘ xl β•‘ β•‘
β•‘ 2 β•‘  β•‘  β•‘ β•‘ l β•‘ β•‘
β•‘ 3 β•‘  β•‘  β•‘ HP β•‘ XXL β•‘ β•‘
β•‘ 4 β•‘  β•‘ β•‘ β•‘ β•‘ β•‘
β•šβ•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•©β•β•β•
+4
1

CASE :

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;

SQL Fiddle with Demo.

Oracle 11g, PIVOT :

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;

. SQL Fiddle with Demo

+2

Source: https://habr.com/ru/post/1527364/


All Articles