WITH material_lookup(material, score) AS ( (VALUES ('metal', 0.15), ('wood', 1), ('resin', 0), ('fabric', 0.5), ('plastic', 0.25) ) ), origin_lookup(origin, score) AS ( (VALUES ('usa', 1), ('imported', 0), ('mixed', 0.5) ) ), unnested_materials AS ( SELECT primary_category, unnest(materials) unnested_material FROM {{ params.products_table }} ), material_scores AS ( SELECT primary_category, AVG(material_lookup.score) AS score FROM unnested_materials JOIN material_lookup ON unnested_materials.unnested_material = material_lookup.material GROUP BY primary_category ), scores AS ( SELECT tcin, material_scores.score AS material_score, weight * 0.75 AS weight_score, packaging * 0.6 AS packaging_score, origin_lookup.score AS origin_score FROM {{ params.products_table }} AS products LEFT JOIN material_scores USING (primary_category) LEFT JOIN origin_lookup USING (origin) ) INSERT INTO {{ params.scored_table }} SELECT tcin, material_score, weight_score, packaging_score, origin_score, material_score + weight_score + packaging_score + origin_score AS score FROM scores;