-- schema version 22 to 23

CREATE VIEW v_stat_modifier AS
SELECT v.year, v.avnr, m.modid, m.name, m.abs, m.rel,
       COUNT(*) AS count,
       MIN(IIF(p.net_amount = 0 AND m.abs IS NULL, NULL, ROUND(COALESCE(d.weight * m.abs, 0) + COALESCE(p.net_amount * m.rel, 0)))) AS min,
       MAX(IIF(p.net_amount = 0 AND m.abs IS NULL, NULL, ROUND(COALESCE(d.weight * m.abs, 0) + COALESCE(p.net_amount * m.rel, 0)))) AS max,
       SUM(ROUND(COALESCE(d.weight * m.abs, 0) + COALESCE(p.net_amount * m.rel, 0))) AS sum
FROM payment_variant v
    JOIN modifier m ON m.year = v.year
    JOIN delivery_part d ON d.year = v.year
    JOIN delivery_part_modifier x ON (x.year, x.did, x.dpnr, x.modid) = (d.year, d.did, d.dpnr, m.modid)
    LEFT JOIN payment_delivery_part p ON (p.year, p.did, p.dpnr, p.avnr) = (d.year, d.did, d.dpnr, v.avnr)
GROUP BY v.year, v.avnr, m.modid
ORDER BY v.year, v.avnr, m.ordering;
