-- schema version 18 to 19

CREATE VIEW v_stat_total AS
SELECT d.year, d.zwstid, v.type, v.sortid,
       IIF(b.discr = a.attrid OR NOT a.area_com, a.attrid, NULL) AS attrid,
       p.cultid, q.qualid,
       IIF(b.discr = '_', 'ungeb', 'geb') AS geb,
       SUM(value) AS weight
FROM delivery_part p
    LEFT JOIN delivery d ON (d.year, d.did) = (p.year, p.did)
    LEFT JOIN wine_variety v ON v.sortid = p.sortid
    LEFT JOIN wine_quality_level q ON q.qualid = p.qualid
    LEFT JOIN delivery_part_bucket b ON (b.year, b.did, b.dpnr) = (p.year, p.did, p.dpnr)
    LEFT JOIN v_wine_attribute a ON a.attrid = p.attrid
GROUP BY d.year, d.zwstid, v.type, v.sortid, IIF(b.discr = a.attrid OR NOT a.area_com, a.attrid, NULL), p.cultid, q.qualid, geb
HAVING SUM(value) > 0
ORDER BY d.year, d.zwstid, v.type DESC, v.sortid, IIF(b.discr = a.attrid OR NOT a.area_com, a.attrid, NULL), p.cultid, q.min_kmw, geb;
