
SELECT
    e.asset_id,
    COUNT(*) AS events,
    SUM(e.downtime_hours * e.prod_rate 
        + e.parts_cost 
        + e.labor_cost 
        + e.env_cost 
        + e.reg_cost 
        + e.safety_cost) AS total_cost_all,
    SUM(e.safety_cost) AS total_safety_cost,
    CASE 
        WHEN SUM(e.downtime_hours * e.prod_rate 
                 + e.parts_cost 
                 + e.labor_cost 
                 + e.env_cost 
                 + e.reg_cost 
                 + e.safety_cost) > 0
        THEN SUM(e.safety_cost) * 1.0
           / SUM(e.downtime_hours * e.prod_rate 
                 + e.parts_cost 
                 + e.labor_cost 
                 + e.env_cost 
                 + e.reg_cost 
                 + e.safety_cost)
        ELSE 0
    END AS safety_share
FROM events e
WHERE e.occurred_on IS NOT NULL
GROUP BY e.asset_id
HAVING total_safety_cost > 0
ORDER BY safety_share DESC;