#!/home/rosy/bin/mariadb

-- Block 1: Create a variable (using a temp table since SQL doesn't have variables across statements easily)
CREATE TEMPORARY TABLE IF NOT EXISTS context (key_name VARCHAR(50) PRIMARY KEY, val INT);
INSERT INTO context VALUES ('top_deliveries', 0) ON DUPLICATE KEY UPDATE val=val;
SELECT 'Created context table' AS status;

-- Block 2: Find the top warehouse and store it
UPDATE context SET val = (
    SELECT SUM(total_shipments)
    FROM daily_delivery_metrics
    WHERE YEAR(report_date) = 2023
    GROUP BY warehouse_id
    ORDER BY SUM(total_shipments) DESC
    LIMIT 1
) WHERE key_name = 'top_deliveries';
SELECT val AS top_deliveries FROM context WHERE key_name = 'top_deliveries';

-- Block 3: Use that stored value to compare all warehouses
SELECT
    warehouse_name,
    SUM(total_shipments) AS total_deliveries,
    (SELECT val FROM context WHERE key_name = 'top_deliveries') AS top,
    ROUND((SUM(total_shipments) - (SELECT val FROM context WHERE key_name = 'top_deliveries'))
          / (SELECT val FROM context WHERE key_name = 'top_deliveries') * 100, 1) AS pct_diff
FROM daily_delivery_metrics
WHERE YEAR(report_date) = 2023
GROUP BY warehouse_id, warehouse_name
ORDER BY total_deliveries DESC;
