{"id":26674208,"url":"https://github.com/harshproj/narwal-rqueries","last_synced_at":"2026-01-06T01:45:31.075Z","repository":{"id":281801431,"uuid":"946463884","full_name":"HarshProj/Narwal-rqueries","owner":"HarshProj","description":null,"archived":false,"fork":false,"pushed_at":"2025-03-11T07:53:37.000Z","size":19,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-11T08:27:54.846Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/HarshProj.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-03-11T07:18:06.000Z","updated_at":"2025-03-11T07:53:41.000Z","dependencies_parsed_at":"2025-03-11T08:38:50.085Z","dependency_job_id":null,"html_url":"https://github.com/HarshProj/Narwal-rqueries","commit_stats":null,"previous_names":["harshproj/narwal-rqueries"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HarshProj%2FNarwal-rqueries","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HarshProj%2FNarwal-rqueries/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HarshProj%2FNarwal-rqueries/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HarshProj%2FNarwal-rqueries/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/HarshProj","download_url":"https://codeload.github.com/HarshProj/Narwal-rqueries/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245573892,"owners_count":20637674,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-03-26T02:18:04.823Z","updated_at":"2026-01-06T01:45:31.052Z","avatar_url":"https://github.com/HarshProj.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Narwal-rqueries\n## ** Average cost per PO (USD) - Monthly average cost for delivery per PO that have completed last mile delivery within the month**\n\n# Delivery Cost Analysis\n\n## Overview\nThis document provides insights into two different SQL queries:\n\n1. **Imports Analysis** - Tracks purchase orders (POs) and total invoice values.\n2. **Delivery Cost Tracking** - Provides accurate cost tracking for deliveries with currency conversion.\n\n## Query 1: Imports Analysis\n\n```sql\nSELECT\n    DATE_TRUNC('month', import_timestamp) AS month,\n    COUNT(id) AS total_pos,\n    SUM(total_invoice_value) AS total_cost,\n    ROUND(AVG(total_invoice_value), 2) AS avg_cost_per_po\nFROM public.imports\nWHERE DATE_PART('month', import_timestamp) = DATE_PART('month', import_timestamp)\nAND DATE_PART('year', import_timestamp) = DATE_PART('year', import_timestamp)\nGROUP BY month\nORDER BY month;\n```\n\n### Purpose:\n- Extracts monthly data on purchase orders (POs) and total invoice values.\n- Computes total and average cost per PO.\n\n---\n\n## Query 2: Delivery Cost Tracking (Recommended)\n\n```sql\nWITH completed_deliveries AS (\n  SELECT\n    DATE_TRUNC('month', d.latest_event_timestamp) as month,\n    d.id as delivery_id\n  FROM deliveries d\n  JOIN shipments s ON d.id = s.delivery_id\n  WHERE s.transport_mode = 'local delivery'\n  AND d.latest_event_timestamp \u003e= '2024-01-01'\n  AND d.latest_event_timestamp \u003c '2025-04-01'\n),\ndelivery_costs AS (\n  SELECT\n    cd.month,\n    dq.quotation_id,\n    -- Convert all costs to USD using approximate exchange rates\n    SUM(\n      CASE qsf.currency\n        WHEN 'USD' THEN qsf.cost * qsf.quantity\n        WHEN 'EUR' THEN qsf.cost * qsf.quantity * 1.08  -- EUR to USD\n        WHEN 'JPY' THEN qsf.cost * qsf.quantity * 0.0067  -- JPY to USD\n        WHEN 'KRW' THEN qsf.cost * qsf.quantity * 0.00075  -- KRW to USD\n        ELSE qsf.cost * qsf.quantity  -- Default to original value if currency not handled\n      END\n    ) as total_cost_usd\n  FROM completed_deliveries cd\n  JOIN delivery_quotations dq ON cd.delivery_id = dq.delivery_id\n  JOIN quotation_schedules qs ON dq.quotation_id = qs.quotation_id\n  JOIN quotation_schedule_fees qsf ON qs.id = qsf.schedule_id\n  GROUP BY cd.month, dq.quotation_id\n)\nSELECT\n  month,\n  COUNT(DISTINCT quotation_id) as number_of_deliveries,\n  SUM(total_cost_usd) as total_cost_usd,\n  ROUND(AVG(total_cost_usd), 2) as avg_cost_per_delivery_usd\nFROM delivery_costs\nGROUP BY month\nORDER BY month DESC;\n```\n\n### Purpose:\n- Tracks the number of deliveries per month.\n- Converts delivery costs into **USD** for accurate cost analysis.\n- Calculates total and average cost per delivery.\n\n---\n\n## Query Output\n\n```json\n{\n    \"success\": true,\n    \"data\": [\n        {\n            \"month\": \"2025-01-31T18:30:00.000Z\",\n            \"number_of_deliveries\": \"294\",\n            \"total_cost_usd\": \"52100304.19150000000000000\",\n            \"avg_cost_per_delivery_usd\": \"177211.92\"\n        },\n        {\n            \"month\": \"2024-12-31T18:30:00.000Z\",\n            \"number_of_deliveries\": \"185\",\n            \"total_cost_usd\": \"1763409.60625000000000000\",\n            \"avg_cost_per_delivery_usd\": \"9531.94\"\n        },\n        {\n            \"month\": \"2024-11-30T18:30:00.000Z\",\n            \"number_of_deliveries\": \"156\",\n            \"total_cost_usd\": \"179175.51185000000000000\",\n            \"avg_cost_per_delivery_usd\": \"1148.56\"\n        },\n        {\n            \"month\": \"2024-10-31T18:30:00.000Z\",\n            \"number_of_deliveries\": \"5\",\n            \"total_cost_usd\": \"3893.40000000000000000\",\n            \"avg_cost_per_delivery_usd\": \"778.68\"\n        }\n    ]\n}\n```\n\n---\n\n\n![image](https://github.com/user-attachments/assets/199fee88-5a08-46f2-a2a3-49ebd927d3db)\n\n\n\n\n\n\n\n\n\n\n\n\n\n## **Average cost per KG (USD) - Monthly average cost for delivery per PO that have completed last mile delivery within the month**\n# Delivery Cost and Weight Report\n\n## SQL Query\n\n```sql\nWITH completed_deliveries AS (\n  SELECT \n    DATE_TRUNC('month', d.latest_event_timestamp) as month,\n    d.id as delivery_id\n  FROM deliveries d\n  JOIN shipments s ON d.id = s.delivery_id\n  WHERE s.transport_mode = 'local delivery'\n  AND d.latest_event_timestamp \u003e= '2024-01-01'\n  AND d.latest_event_timestamp \u003c '2025-04-01'\n),\ndelivery_weights AS (\n  -- Get weights from quotation packages\n  SELECT \n    cd.month,\n    cd.delivery_id,\n    SUM(qp.weight) as total_weight\n  FROM completed_deliveries cd\n  JOIN delivery_quotations dq ON cd.delivery_id = dq.delivery_id\n  JOIN quotation_packages qp ON dq.quotation_id = qp.quotation_id\n  GROUP BY cd.month, cd.delivery_id\n),\ndelivery_costs AS (\n  SELECT \n    cd.month,\n    cd.delivery_id,\n    -- Convert all costs to USD using approximate exchange rates\n    SUM(\n      CASE qsf.currency\n        WHEN 'USD' THEN qsf.cost * qsf.quantity\n        WHEN 'EUR' THEN qsf.cost * qsf.quantity * 1.08  -- EUR to USD\n        WHEN 'JPY' THEN qsf.cost * qsf.quantity * 0.0067  -- JPY to USD\n        WHEN 'KRW' THEN qsf.cost * qsf.quantity * 0.00075  -- KRW to USD\n        ELSE qsf.cost * qsf.quantity  -- Default to original value if currency not handled\n      END\n    ) as total_cost_usd\n  FROM completed_deliveries cd\n  JOIN delivery_quotations dq ON cd.delivery_id = dq.delivery_id\n  JOIN quotation_schedules qs ON dq.quotation_id = qs.quotation_id\n  JOIN quotation_schedule_fees qsf ON qs.id = qsf.schedule_id\n  GROUP BY cd.month, cd.delivery_id\n)\nSELECT \n  dw.month,\n  COUNT(DISTINCT dw.delivery_id) as number_of_deliveries,\n  ROUND(SUM(dw.total_weight), 2) as total_weight_kg,\n  ROUND(SUM(dc.total_cost_usd), 2) as total_cost_usd,\n  ROUND(SUM(dc.total_cost_usd) / NULLIF(SUM(dw.total_weight), 0), 2) as avg_cost_per_kg_usd\nFROM delivery_weights dw\nJOIN delivery_costs dc ON dw.delivery_id = dc.delivery_id AND dw.month = dc.month\nWHERE dw.total_weight \u003e 0  -- Exclude deliveries with no weight data\nGROUP BY dw.month\nORDER BY dw.month DESC;\n```\n\n## Output\n\n```json\n{\n    \"success\": true,\n    \"data\": [\n        {\n            \"month\": \"2025-01-31T18:30:00.000Z\",\n            \"number_of_deliveries\": \"3117\",\n            \"total_weight_kg\": \"43264055.42\",\n            \"total_cost_usd\": \"52100304.19\",\n            \"avg_cost_per_kg_usd\": \"1.20\"\n        },\n        {\n            \"month\": \"2024-12-31T18:30:00.000Z\",\n            \"number_of_deliveries\": \"1520\",\n            \"total_weight_kg\": \"5405754.09\",\n            \"total_cost_usd\": \"1763409.61\",\n            \"avg_cost_per_kg_usd\": \"0.33\"\n        },\n        {\n            \"month\": \"2024-11-30T18:30:00.000Z\",\n            \"number_of_deliveries\": \"441\",\n            \"total_weight_kg\": \"310377.20\",\n            \"total_cost_usd\": \"179175.51\",\n            \"avg_cost_per_kg_usd\": \"0.58\"\n        },\n        {\n            \"month\": \"2024-10-31T18:30:00.000Z\",\n            \"number_of_deliveries\": \"5\",\n            \"total_weight_kg\": \"1341.60\",\n            \"total_cost_usd\": \"3893.40\",\n            \"avg_cost_per_kg_usd\": \"2.90\"\n        }...\n    ]\n}\n```\n\n![image](https://github.com/user-attachments/assets/4360ad0c-f862-4ff5-8a54-c239f0947dec)\n\n\n## **Cargo volumes in CBM - Monthly volume of inbound and outbound cargo in total and also by hub**\n# Shipment Volume Report\n\n## Overview\nThis project provides SQL queries to calculate monthly shipment volumes based on import and export data. Depending on whether shipment records track both imports and exports together or independently, different queries are used to compute the shipment volume.\n\n## Queries\n\n### Query 1: Independent Imports and Exports\nUse this query when import and export records are managed separately and shipments do not always track both activities.\n\n```sql\nSELECT\n    DATE_TRUNC('month', s.latest_event_timestamp) AS month,\n    s.origin_city AS hub,\n    SUM(COALESCE(ip.cbm, 0)) AS inbound_volume,\n    SUM(COALESCE(ep.cbm, 0)) AS outbound_volume,\n    SUM(COALESCE(ip.cbm, 0) + COALESCE(ep.cbm, 0)) AS total_volume\nFROM shipments s\nLEFT JOIN import_packages ip ON s.id = ip.import_id  -- Inbound shipments\nLEFT JOIN export_packages ep ON s.id = ep.export_id  -- Outbound shipments\nWHERE s.latest_event_timestamp IS NOT NULL  \nGROUP BY month, hub\nORDER BY month DESC, hub;\n```\n\n### Query 2: Integrated Shipment Tracking\nUse this query when shipment records reliably track both imports and exports.\n\n```sql\nWITH monthly_exports AS (\n  SELECT\n    DATE_TRUNC('month', e.export_timestamp) AS month,\n    e.port_from as hub,\n    SUM(ep.cbm) as total_cbm\n  FROM exports e\n  JOIN export_packages ep ON e.id = ep.export_id\n  WHERE e.export_timestamp IS NOT NULL\n  GROUP BY DATE_TRUNC('month', e.export_timestamp), e.port_from\n),\nmonthly_imports AS (\n  SELECT\n    DATE_TRUNC('month', i.import_timestamp) AS month,\n    i.warehouse as hub,\n    SUM(ip.cbm) as total_cbm\n  FROM imports i\n  JOIN import_packages ip ON i.id = ip.import_id\n  WHERE i.import_timestamp IS NOT NULL\n  GROUP BY DATE_TRUNC('month', i.import_timestamp), i.warehouse\n)\nSELECT\n  COALESCE(e.month, i.month) as month,\n  COALESCE(e.hub, i.hub) as hub,\n  COALESCE(e.total_cbm, 0) as export_cbm,\n  COALESCE(i.total_cbm, 0) as import_cbm,\n  COALESCE(e.total_cbm, 0) + COALESCE(i.total_cbm, 0) as total_cbm\nFROM monthly_exports e\nFULL OUTER JOIN monthly_imports i\n  ON e.month = i.month\n  AND e.hub = i.hub\nWHERE COALESCE(e.month, i.month) IS NOT NULL\nORDER BY month DESC, hub;\n```\n\n## Output Example\nThe query returns shipment volumes in the following JSON format:\n\n```json\n{\n    \"success\": true,\n    \"data\": [\n        {\n            \"month\": \"2025-11-30T18:30:00.000Z\",\n            \"hub\": null,\n            \"export_cbm\": \"19.05800\",\n            \"import_cbm\": \"0\",\n            \"total_cbm\": \"19.05800\"\n        },\n        {\n            \"month\": \"2025-01-31T18:30:00.000Z\",\n            \"hub\": \"1F\",\n            \"export_cbm\": \"0\",\n            \"import_cbm\": \"1149.90900\",\n            \"total_cbm\": \"1149.90900\"\n        },\n        {\n            \"month\": \"2025-01-31T18:30:00.000Z\",\n            \"hub\": \"ICN\",\n            \"export_cbm\": \"158.67700\",\n            \"import_cbm\": \"0\",\n            \"total_cbm\": \"158.67700\"\n        }...\n    ]\n}\n```\n\n\n\n![image](https://github.com/user-attachments/assets/dcbec013-eb90-4711-9960-20628a694707)\n\n\n\n\n## **List of High-cost shipment - Monthly list of high-cost delivery (only including shipment cost) that have completed onboard last mile delivery within the month**\n# Monthly Shipments Report\n\n## Overview\nThis SQL query retrieves and aggregates shipment data for the last three months, including details like shipment ID, customer, origin, destination, transport mode, latest event timestamp, total cost, and currency. The results are grouped by month and ordered by the highest total cost within each month, limited to the top 100 records.\n\n## SQL Query\n```sql\nWITH monthly_shipments AS (\n    SELECT\n        s.id as shipment_id,\n        s.customer,\n        s.origin,\n        s.destination,\n        s.transport_mode,\n        s.latest_event_timestamp,\n        DATE_TRUNC('month', s.latest_event_timestamp) as delivery_month,\n        dq.quotation_id,\n        SUM(qsf.cost * qsf.quantity) as total_cost,\n        qsf.currency\n    FROM shipments s\n    JOIN deliveries d ON s.delivery_id = d.id\n    JOIN delivery_quotations dq ON d.id = dq.delivery_id\n    JOIN quotation_schedules qs ON dq.quotation_id = qs.quotation_id\n    JOIN quotation_schedule_fees qsf ON qs.id = qsf.schedule_id\n    WHERE s.latest_event_timestamp \u003e= (CURRENT_DATE - INTERVAL '3 months')\n    AND s.latest_event_timestamp \u003c CURRENT_DATE\n    GROUP BY\n        s.id,\n        s.customer,\n        s.origin,\n        s.destination,\n        s.transport_mode,\n        s.latest_event_timestamp,\n        DATE_TRUNC('month', s.latest_event_timestamp),\n        dq.quotation_id,\n        qsf.currency\n)\nSELECT\n    TO_CHAR(delivery_month, 'YYYY-MM') as month,\n    shipment_id,\n    customer,\n    origin,\n    destination,\n    transport_mode,\n    TO_CHAR(latest_event_timestamp, 'YYYY-MM-DD') as delivery_date,\n    ROUND(total_cost, 2) as total_cost,\n    currency\nFROM monthly_shipments\nORDER BY\n    delivery_month DESC,\n    total_cost DESC\nLIMIT 100;\n```\n\n## Output\n```json\n{\n    \"success\": true,\n    \"data\": [\n        {\n            \"month\": \"2025-02\",\n            \"shipment_id\": \"523809\",\n            \"customer\": \"60YC\",\n            \"origin\": \"JPUKB\",\n            \"destination\": \"JPKII\",\n            \"transport_mode\": \"local delivery\",\n            \"delivery_date\": \"2025-02-14\",\n            \"total_cost\": \"12060690.00\",\n            \"currency\": \"KRW\"\n        },\n        {\n            \"month\": \"2025-02\",\n            \"shipment_id\": \"523791\",\n            \"customer\": \"60YC\",\n            \"origin\": \"JPUKB\",\n            \"destination\": \"JPKII\",\n            \"transport_mode\": \"local delivery\",\n            \"delivery_date\": \"2025-02-14\",\n            \"total_cost\": \"12060690.00\",\n            \"currency\": \"KRW\"\n        },\n        {\n            \"month\": \"2025-02\",\n            \"shipment_id\": \"523802\",\n            \"customer\": \"60YC\",\n            \"origin\": \"JPUKB\",\n            \"destination\": \"JPKII\",\n            \"transport_mode\": \"local delivery\",\n            \"delivery_date\": \"2025-02-14\",\n            \"total_cost\": \"12060690.00\",\n            \"currency\": \"KRW\"\n        },\n        {\n            \"month\": \"2025-02\",\n            \"shipment_id\": \"523804\",\n            \"customer\": \"60YC\",\n            \"origin\": \"JPUKB\",\n            \"destination\": \"JPKII\",\n            \"transport_mode\": \"local delivery\",\n            \"delivery_date\": \"2025-02-14\",\n            \"total_cost\": \"12060690.00\",\n            \"currency\": \"KRW\"\n        },\n        {\n            \"month\": \"2025-02\",\n            \"shipment_id\": \"523796\",\n            \"customer\": \"60YC\",\n            \"origin\": \"JPUKB\",\n            \"destination\": \"JPKII\",\n            \"transport_mode\": \"local delivery\",\n            \"delivery_date\": \"2025-02-14\",\n            \"total_cost\": \"12060690.00\",\n            \"currency\": \"KRW\"\n        }\n    ]\n}\n```\n\n## Explanation\n1. **CTE (`WITH monthly_shipments AS (...)`)**:\n   - Fetches shipment details from the `shipments` table.\n   - Joins multiple related tables (`deliveries`, `delivery_quotations`, `quotation_schedules`, `quotation_schedule_fees`).\n   - Filters shipments from the last three months.\n   - Groups by shipment ID, customer, origin, destination, transport mode, and currency.\n   - Calculates the `total_cost` for each shipment.\n\n2. **Main Query (`SELECT ... FROM monthly_shipments`)**:\n   - Formats `delivery_month` as `YYYY-MM`.\n   - Formats `latest_event_timestamp` as `YYYY-MM-DD`.\n   - Sorts the results by `delivery_month DESC` and `total_cost DESC`.\n   - Limits the output to the top 100 shipments.\n\n\n![image](https://github.com/user-attachments/assets/60f10a1a-e9e4-43c9-a347-2ac5f89d6ba3)\n\n\n## //Ratio on freight mode - Monthly ratio of freight modes based on cost, number of POs, and weight. Total ratio including all the shipments and ratio by hub is required.\n# Optimized SQL Query for Monthly Shipment Metrics\n\n## Overview\nThis query calculates monthly shipment metrics, including purchase order count, shipment count, total weight, and total cost in USD. It also computes the ratio of each metric relative to total and hub-specific values.\n\n## Optimized SQL Query\n```sql\nWITH monthly_metrics AS (\n  SELECT\n    DATE_TRUNC('month', s.latest_event_timestamp) AS month,\n    s.transport_mode,\n    s.origin AS hub,\n    COUNT(DISTINCT po.number) AS po_count,\n    COUNT(DISTINCT s.id) AS shipment_count,\n    SUM(qp.weight) AS total_weight,\n    SUM(\n      CASE qsf.currency\n        WHEN 'USD' THEN qsf.cost * qsf.quantity\n        WHEN 'EUR' THEN qsf.cost * qsf.quantity * 1.08\n        WHEN 'JPY' THEN qsf.cost * qsf.quantity * 0.0067\n        WHEN 'KRW' THEN qsf.cost * qsf.quantity * 0.00075\n      END\n    ) AS total_cost_usd\n  FROM shipments s\n  LEFT JOIN deliveries d ON s.delivery_id = d.id\n  LEFT JOIN delivery_quotations dq ON d.id = dq.delivery_id\n  LEFT JOIN quotations q ON dq.quotation_id = q.id\n  LEFT JOIN quotation_packages qp ON q.id = qp.quotation_id\n  LEFT JOIN quotation_schedule_fees qsf ON q.id = qsf.schedule_id\n  LEFT JOIN export_package_po_numbers epn ON epn.export_package_id = qp.id\n  LEFT JOIN purchase_orders po ON epn.po_number = po.number\n  WHERE s.latest_event_timestamp \u003e= '2024-01-01'\n    AND s.latest_event_timestamp \u003c '2025-04-01'\n  GROUP BY\n    DATE_TRUNC('month', s.latest_event_timestamp),\n    s.transport_mode,\n    s.origin\n),\nmonthly_totals AS (\n  SELECT\n    month,\n    SUM(po_count) AS total_po_count,\n    SUM(shipment_count) AS total_shipment_count,\n    SUM(total_weight) AS total_weight,\n    SUM(total_cost_usd) AS total_cost_usd\n  FROM monthly_metrics\n  GROUP BY month\n),\nhub_totals AS (\n  SELECT\n    month,\n    hub,\n    SUM(po_count) AS hub_po_count,\n    SUM(shipment_count) AS hub_shipment_count,\n    SUM(total_weight) AS hub_weight,\n    SUM(total_cost_usd) AS hub_cost_usd\n  FROM monthly_metrics\n  GROUP BY month, hub\n)\nSELECT\n  mm.month,\n  mm.hub,\n  mm.transport_mode,\n  mm.po_count,\n  ROUND(mm.po_count * 100.0 / NULLIF(mt.total_po_count, 0), 2) AS po_ratio_total,\n  ROUND(mm.po_count * 100.0 / NULLIF(ht.hub_po_count, 0), 2) AS po_ratio_hub,\n  mm.shipment_count,\n  ROUND(mm.shipment_count * 100.0 / NULLIF(mt.total_shipment_count, 0), 2) AS shipment_ratio_total,\n  ROUND(mm.shipment_count * 100.0 / NULLIF(ht.hub_shipment_count, 0), 2) AS shipment_ratio_hub,\n  ROUND(mm.total_weight, 2) AS total_weight_kg,\n  ROUND(mm.total_weight * 100.0 / NULLIF(mt.total_weight, 0), 2) AS weight_ratio_total,\n  ROUND(mm.total_weight * 100.0 / NULLIF(ht.hub_weight, 0), 2) AS weight_ratio_hub,\n  ROUND(mm.total_cost_usd, 2) AS total_cost_usd,\n  ROUND(mm.total_cost_usd * 100.0 / NULLIF(mt.total_cost_usd, 0), 2) AS cost_ratio_total,\n  ROUND(mm.total_cost_usd * 100.0 / NULLIF(ht.hub_cost_usd, 0), 2) AS cost_ratio_hub\nFROM monthly_metrics mm\nJOIN monthly_totals mt ON mm.month = mt.month\nJOIN hub_totals ht ON mm.month = ht.month AND mm.hub = ht.hub\nWHERE mm.transport_mode IS NOT NULL\nORDER BY\n  mm.month DESC,\n  mm.hub,\n  mm.total_cost_usd DESC;\n```\n\n## Sample Output\n```json\n{\n    \"success\": true,\n    \"data\": [\n        {\n            \"month\": \"2025-01-31T18:30:00.000Z\",\n            \"hub\": \"AMS\",\n            \"transport_mode\": \"local delivery\",\n            \"po_count\": \"0\",\n            \"po_ratio_total\": \"0.00\",\n            \"po_ratio_hub\": \"0.00\",\n            \"shipment_count\": \"1\",\n            \"shipment_ratio_total\": \"0.00\",\n            \"shipment_ratio_hub\": \"2.13\",\n            \"total_weight_kg\": null,\n            \"weight_ratio_total\": null,\n            \"weight_ratio_hub\": null,\n            \"total_cost_usd\": null,\n            \"cost_ratio_total\": null,\n            \"cost_ratio_hub\": null\n        },\n        {\n            \"month\": \"2025-01-31T18:30:00.000Z\",\n            \"hub\": \"AMS\",\n            \"transport_mode\": \"air freight\",\n            \"po_count\": \"111\",\n            \"po_ratio_total\": \"2.81\",\n            \"po_ratio_hub\": \"100.00\",\n            \"shipment_count\": \"46\",\n            \"shipment_ratio_total\": \"0.02\",\n            \"shipment_ratio_hub\": \"97.87\",\n            \"total_weight_kg\": \"4156.34\",\n            \"weight_ratio_total\": \"0.00\",\n            \"weight_ratio_hub\": \"100.00\",\n            \"total_cost_usd\": \"120800.83\",\n            \"cost_ratio_total\": \"0.01\",\n            \"cost_ratio_hub\": \"100.00\"\n        }\n    ]\n}\n```\n\n## Explanation\n- **`monthly_metrics` CTE**: Computes monthly aggregated shipment metrics.\n- **`monthly_totals` CTE**: Summarizes total counts and values per month.\n- **`hub_totals` CTE**: Aggregates totals for each hub per month.\n- **Final Query**: Joins all CTEs and calculates percentages to compare shipments, weight, and cost across hubs and transport modes.\n\n## Use Cases\n- Track shipment trends over time.\n- Compare performance across different hubs and transport modes.\n- Monitor costs in a unified currency (USD).\n- Optimize logistics and resource allocation.\n\n\n![image](https://github.com/user-attachments/assets/bf53a258-b098-4a04-93d1-2e40db3c8c11)\n\n\n## // Ratio of key hub vs non-key hub (based on cost, number of POs, and weight) - Monthly ratio of completed last-mile delivery at key hubs vs non-key hubs based on cost, number of POs, and weight.\n```\n WITH delivery_metrics AS (\n  SELECT \n    DATE_TRUNC('month', s.latest_event_timestamp) as month,\n    CASE \n      WHEN s.origin IN ('ICN', 'JPUKB', 'KRPUS') THEN 'Key Hub'\n      ELSE 'Non-Key Hub'\n    END as hub_type,\n    s.origin as hub,\n    -- Count distinct POs\n    COUNT(DISTINCT po.number) as po_count,\n    -- Count shipments\n    COUNT(DISTINCT s.id) as shipment_count,\n    -- Sum weights\n    SUM(qp.weight) as total_weight,\n    -- Calculate costs in USD\n    SUM(\n      CASE qsf.currency\n        WHEN 'USD' THEN qsf.cost * qsf.quantity\n        WHEN 'EUR' THEN qsf.cost * qsf.quantity * 1.08  -- Approximate EUR to USD\n        WHEN 'JPY' THEN qsf.cost * qsf.quantity * 0.0067  -- Approximate JPY to USD\n        WHEN 'KRW' THEN qsf.cost * qsf.quantity * 0.00075  -- Approximate KRW to USD\n      END\n    ) as total_cost_usd,\n    -- Count completed last mile deliveries\n    COUNT(DISTINCT CASE \n      WHEN s.transport_mode = 'local delivery' \n      AND d.latest_event_timestamp IS NOT NULL \n      THEN s.id \n    END) as completed_last_mile_count,\n    -- Sum weight of completed last mile deliveries\n    SUM(CASE \n      WHEN s.transport_mode = 'local delivery' \n      AND d.latest_event_timestamp IS NOT NULL \n      THEN qp.weight \n      ELSE 0 \n    END) as completed_last_mile_weight,\n    -- Sum cost of completed last mile deliveries\n    SUM(CASE \n      WHEN s.transport_mode = 'local delivery' \n      AND d.latest_event_timestamp IS NOT NULL \n      THEN \n        CASE qsf.currency\n          WHEN 'USD' THEN qsf.cost * qsf.quantity\n          WHEN 'EUR' THEN qsf.cost * qsf.quantity * 1.08\n          WHEN 'JPY' THEN qsf.cost * qsf.quantity * 0.0067\n          WHEN 'KRW' THEN qsf.cost * qsf.quantity * 0.00075\n        END\n      ELSE 0 \n    END) as completed_last_mile_cost_usd\n  FROM shipments s\n  LEFT JOIN deliveries d ON s.delivery_id = d.id\n  LEFT JOIN delivery_quotations dq ON d.id = dq.delivery_id\n  LEFT JOIN quotations q ON dq.quotation_id = q.id\n  LEFT JOIN quotation_packages qp ON q.id = qp.quotation_id\n  LEFT JOIN quotation_schedules qs ON q.id = qs.quotation_id\n  LEFT JOIN quotation_schedule_fees qsf ON qs.id = qsf.schedule_id\n  LEFT JOIN export_package_po_numbers epn ON epn.export_package_id = qp.id\n  LEFT JOIN purchase_orders po ON epn.po_number = po.number\n  WHERE s.latest_event_timestamp \u003e= '2024-01-01'\n  AND s.latest_event_timestamp \u003c '2025-04-01'\n  GROUP BY \n    DATE_TRUNC('month', s.latest_event_timestamp),\n    hub_type,\n    s.origin\n),\nmonthly_totals AS (\n  SELECT \n    month,\n    SUM(po_count) as total_po_count,\n    SUM(shipment_count) as total_shipment_count,\n    SUM(total_weight) as total_weight,\n    SUM(total_cost_usd) as total_cost_usd,\n    SUM(completed_last_mile_count) as total_completed_last_mile_count,\n    SUM(completed_last_mile_weight) as total_completed_last_mile_weight,\n    SUM(completed_last_mile_cost_usd) as total_completed_last_mile_cost_usd\n  FROM delivery_metrics\n  GROUP BY month\n)\n\nSELECT \n  dm.month,\n  dm.hub_type,\n  dm.hub,\n  -- Overall metrics\n  dm.po_count,\n  ROUND(dm.po_count * 100.0 / NULLIF(mt.total_po_count, 0), 2) as po_ratio,\n  dm.shipment_count,\n  ROUND(dm.shipment_count * 100.0 / NULLIF(mt.total_shipment_count, 0), 2) as shipment_ratio,\n  ROUND(dm.total_weight, 2) as total_weight_kg,\n  ROUND(dm.total_weight * 100.0 / NULLIF(mt.total_weight, 0), 2) as weight_ratio,\n  ROUND(dm.total_cost_usd, 2) as total_cost_usd,\n  ROUND(dm.total_cost_usd * 100.0 / NULLIF(mt.total_cost_usd, 0), 2) as cost_ratio,\n  -- Last mile delivery metrics\n  dm.completed_last_mile_count,\n  ROUND(dm.completed_last_mile_count * 100.0 / NULLIF(mt.total_completed_last_mile_count, 0), 2) as last_mile_count_ratio,\n  ROUND(dm.completed_last_mile_weight, 2) as completed_last_mile_weight_kg,\n  ROUND(dm.completed_last_mile_weight * 100.0 / NULLIF(mt.total_completed_last_mile_weight, 0), 2) as last_mile_weight_ratio,\n  ROUND(dm.completed_last_mile_cost_usd, 2) as completed_last_mile_cost_usd,\n  ROUND(dm.completed_last_mile_cost_usd * 100.0 / NULLIF(mt.total_completed_last_mile_cost_usd, 0), 2) as last_mile_cost_ratio,\n  -- Last mile completion rates within hub\n  ROUND(dm.completed_last_mile_count * 100.0 / NULLIF(dm.shipment_count, 0), 2) as hub_last_mile_completion_rate,\n  ROUND(dm.completed_last_mile_weight * 100.0 / NULLIF(dm.total_weight, 0), 2) as hub_weight_completion_rate,\n  ROUND(dm.completed_last_mile_cost_usd * 100.0 / NULLIF(dm.total_cost_usd, 0), 2) as hub_cost_completion_rate\nFROM delivery_metrics dm\nJOIN monthly_totals mt ON dm.month = mt.month\nWHERE dm.month \u003e= '2025-01-01'  -- Focus on recent months\nORDER BY \n  dm.month DESC,\n  dm.hub_type,\n  dm.total_cost_usd DESC;\n\n```\n```\n/*Output*/\n{\n    \"success\": true,\n    \"data\": [\n        {\n            \"month\": \"2025-01-31T18:30:00.000Z\",\n            \"hub_type\": \"Key Hub\",\n            \"hub\": \"ICN\",\n            \"po_count\": \"721\",\n            \"po_ratio\": \"19.05\",\n            \"shipment_count\": \"612\",\n            \"shipment_ratio\": \"0.20\",\n            \"total_weight_kg\": \"31616585.18\",\n            \"weight_ratio\": \"20.15\",\n            \"total_cost_usd\": \"189103560.36\",\n            \"cost_ratio\": \"21.48\",\n            \"completed_last_mile_count\": \"434\",\n            \"last_mile_count_ratio\": \"0.14\",\n            \"completed_last_mile_weight_kg\": \"31019974.92\",\n            \"last_mile_weight_ratio\": \"20.29\",\n            \"completed_last_mile_cost_usd\": \"184082963.61\",\n            \"last_mile_cost_ratio\": \"21.43\",\n            \"hub_last_mile_completion_rate\": \"70.92\",\n            \"hub_weight_completion_rate\": \"98.11\",\n            \"hub_cost_completion_rate\": \"97.35\"\n        },\n        {\n            \"month\": \"2025-01-31T18:30:00.000Z\",\n            \"hub_type\": \"Key Hub\",\n            \"hub\": \"KRPUS\",\n            \"po_count\": \"422\",\n            \"po_ratio\": \"11.15\",\n            \"shipment_count\": \"2656\",\n            \"shipment_ratio\": \"0.87\",\n            \"total_weight_kg\": \"3299252.04\",\n            \"weight_ratio\": \"2.10\",\n            \"total_cost_usd\": \"14408073.50\",\n            \"cost_ratio\": \"1.64\",\n            \"completed_last_mile_count\": \"1\",\n            \"last_mile_count_ratio\": \"0.00\",\n            \"completed_last_mile_weight_kg\": \"154371.50\",\n            \"last_mile_weight_ratio\": \"0.10\",\n            \"completed_last_mile_cost_usd\": \"160325.00\",\n            \"last_mile_cost_ratio\": \"0.02\",\n            \"hub_last_mile_completion_rate\": \"0.04\",\n            \"hub_weight_completion_rate\": \"4.68\",\n            \"hub_cost_completion_rate\": \"1.11\"\n        },\n        {\n            \"month\": \"2025-01-31T18:30:00.000Z\",\n            \"hub_type\": \"Key Hub\",\n            \"hub\": \"JPUKB\",\n            \"po_count\": \"713\",\n            \"po_ratio\": \"18.84\",\n            \"shipment_count\": \"294974\",\n            \"shipment_ratio\": \"96.55\",\n            \"total_weight_kg\": \"324476.81\",\n            \"weight_ratio\": \"0.21\",\n            \"total_cost_usd\": \"2507634.20\",\n            \"cost_ratio\": \"0.28\",\n            \"completed_last_mile_count\": \"294947\",\n            \"last_mile_count_ratio\": \"98.28\",\n            \"completed_last_mile_weight_kg\": \"312803.91\",\n            \"last_mile_weight_ratio\": \"0.20\",\n            \"completed_last_mile_cost_usd\": \"1967489.07\",\n            \"last_mile_cost_ratio\": \"0.23\",\n            \"hub_last_mile_completion_rate\": \"99.99\",\n            \"hub_weight_completion_rate\": \"96.40\",\n            \"hub_cost_completion_rate\": \"78.46\"\n        },\n        {\n            \"month\": \"2025-01-31T18:30:00.000Z\",\n            \"hub_type\": \"Non-Key Hub\",\n            \"hub\": \"JPCHI\",\n            \"po_count\": \"0\",\n            \"po_ratio\": \"0.00\",\n            \"shipment_count\": \"1\",\n            \"shipment_ratio\": \"0.00\",\n            \"total_weight_kg\": null,\n            \"weight_ratio\": null,\n            \"total_cost_usd\": null,\n            \"cost_ratio\": null,\n            \"completed_last_mile_count\": \"0\",\n            \"last_mile_count_ratio\": \"0.00\",\n            \"completed_last_mile_weight_kg\": \"0.00\",\n            \"last_mile_weight_ratio\": \"0.00\",\n            \"completed_last_mile_cost_usd\": \"0.00\",\n            \"last_mile_cost_ratio\": \"0.00\",\n            \"hub_last_mile_completion_rate\": \"0.00\",\n            \"hub_weight_completion_rate\": null,\n            \"hub_cost_completion_rate\": null\n        },\n        {\n            \"month\": \"2025-01-31T18:30:00.000Z\",\n            \"hub_type\": \"Non-Key Hub\",\n            \"hub\": null,\n            \"po_count\": \"1584\",\n            \"po_ratio\": \"41.85\",\n            \"shipment_count\": \"7103\",\n            \"shipment_ratio\": \"2.32\",\n            \"total_weight_kg\": \"121541540.53\",\n            \"weight_ratio\": \"77.47\",\n            \"total_cost_usd\": \"673075596.72\",\n            \"cost_ratio\": \"76.47\",\n            \"completed_last_mile_count\": \"4702\",\n            \"last_mile_count_ratio\": \"1.57\",\n            \"completed_last_mile_weight_kg\": \"121414784.57\",\n            \"last_mile_weight_ratio\": \"79.41\",\n            \"completed_last_mile_cost_usd\": \"672835520.96\",\n            \"last_mile_cost_ratio\": \"78.32\",\n            \"hub_last_mile_completion_rate\": \"66.20\",\n            \"hub_weight_completion_rate\": \"99.90\",\n            \"hub_cost_completion_rate\": \"99.96\"\n        },\n        {\n            \"month\": \"2025-01-31T18:30:00.000Z\",\n            \"hub_type\": \"Non-Key Hub\",\n            \"hub\": \"KIX\",\n            \"po_count\": \"190\",\n            \"po_ratio\": \"5.02\",\n            \"shipment_count\": \"83\",\n            \"shipment_ratio\": \"0.03\",\n            \"total_weight_kg\": \"77913.70\",\n            \"weight_ratio\": \"0.05\",\n            \"total_cost_usd\": \"872881.75\",\n            \"cost_ratio\": \"0.10\",\n            \"completed_last_mile_count\": \"0\",\n            \"last_mile_count_ratio\": \"0.00\",\n            \"completed_last_mile_weight_kg\": \"0.00\",\n            \"last_mile_weight_ratio\": \"0.00\",\n            \"completed_last_mile_cost_usd\": \"0.00\",\n            \"last_mile_cost_ratio\": \"0.00\",\n            \"hub_last_mile_completion_rate\": \"0.00\",\n            \"hub_weight_completion_rate\": \"0.00\",\n            \"hub_cost_completion_rate\": \"0.00\"\n        },\n        {\n            \"month\": \"2025-01-31T18:30:00.000Z\",\n            \"hub_type\": \"Non-Key Hub\",\n            \"hub\": \"AMS\",\n            \"po_count\": \"111\",\n            \"po_ratio\": \"2.93\",\n            \"shipment_count\": \"47\",\n            \"shipment_ratio\": \"0.02\",\n            \"total_weight_kg\": \"4156.34\",\n            \"weight_ratio\": \"0.00\",\n            \"total_cost_usd\": \"120800.83\",\n            \"cost_ratio\": \"0.01\",\n            \"completed_last_mile_count\": \"1\",\n            \"last_mile_count_ratio\": \"0.00\",\n            \"completed_last_mile_weight_kg\": \"0.00\",\n            \"last_mile_weight_ratio\": \"0.00\",\n            \"completed_last_mile_cost_usd\": \"0.00\",\n            \"last_mile_cost_ratio\": \"0.00\",\n            \"hub_last_mile_completion_rate\": \"2.13\",\n            \"hub_weight_completion_rate\": \"0.00\",\n            \"hub_cost_completion_rate\": \"0.00\"\n        },\n        ...]\n}\n```\n\n![image](https://github.com/user-attachments/assets/8432b1d3-9801-475c-8912-c34e25e4fa8e)\n\n\n## //Consolidation Rate - Number of POs shipped / Number of shipments for air freight, sea freight, and trucking.\n```\n WITH storage_durations AS (\n    SELECT \n        DATE_TRUNC('month', de.event_timestamp) as month,\n        s.origin as hub,\n        s.origin_city,\n        s.id as shipment_id,\n        -- Get first arrival event\n        MIN(de.event_timestamp) as arrival_date,\n        -- Get last departure event\n        MAX(de.event_timestamp) as departure_date,\n        -- Calculate storage duration in days\n        EXTRACT(EPOCH FROM (MAX(de.event_timestamp) - MIN(de.event_timestamp)))/86400.0 as storage_days\n    FROM shipments s\n    JOIN delivery_events de ON s.delivery_id = de.delivery_id\n    WHERE \n        -- Focus on most recent data\n        de.event_timestamp \u003e= '2025-02-01'\n        AND de.event_timestamp \u003c '2025-03-01'\n        -- Ensure valid storage duration\n        AND s.latest_event_timestamp \u003e s.earliest_event_timestamp\n        AND s.origin IS NOT NULL\n    GROUP BY \n        DATE_TRUNC('month', de.event_timestamp),\n        s.origin,\n        s.origin_city,\n        s.id\n    HAVING \n        MIN(de.event_timestamp) != MAX(de.event_timestamp)\n)\n\nSELECT \n    month,\n    hub,\n    origin_city,\n    -- Volume metrics\n    COUNT(DISTINCT shipment_id) as total_shipments,\n    -- Storage duration metrics\n    ROUND(AVG(storage_days)::numeric, 2) as avg_storage_days,\n    ROUND(MIN(storage_days)::numeric, 2) as min_storage_days,\n    ROUND(MAX(storage_days)::numeric, 2) as max_storage_days,\n    ROUND(PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY storage_days)::numeric, 2) as median_storage_days,\n    -- Storage duration distribution\n    COUNT(CASE WHEN storage_days \u003c= 7 THEN 1 END) as within_week,\n    COUNT(CASE WHEN storage_days \u003e 7 AND storage_days \u003c= 14 THEN 1 END) as within_two_weeks,\n    COUNT(CASE WHEN storage_days \u003e 14 AND storage_days \u003c= 30 THEN 1 END) as within_month,\n    COUNT(CASE WHEN storage_days \u003e 30 THEN 1 END) as over_month,\n    -- Storage efficiency metrics\n    ROUND(COUNT(CASE WHEN storage_days \u003c= 7 THEN 1 END)::numeric * 100 / \n        NULLIF(COUNT(*), 0)::numeric, 2) as within_week_percentage,\n    ROUND(COUNT(CASE WHEN storage_days \u003c= 14 THEN 1 END)::numeric * 100 / \n        NULLIF(COUNT(*), 0)::numeric, 2) as within_two_weeks_percentage,\n    -- Additional metrics for analysis\n    ROUND(STDDEV(storage_days)::numeric, 2) as storage_days_stddev\nFROM storage_durations\nGROUP BY \n    month,\n    hub,\n    origin_city\nHAVING COUNT(DISTINCT shipment_id) \u003e 0\nORDER BY \n    avg_storage_days DESC\nLIMIT 100;\n```\n\n![image](https://github.com/user-attachments/assets/5b6e05e1-cb55-4123-af34-0caf43c6e29b)\n![image](https://github.com/user-attachments/assets/ae4b9bde-2a13-4691-9a31-6b05c880d496)\n\n/*Output*/\n```\n{\n    \"success\": true,\n    \"data\": [\n        {\n            \"month\": \"2025-01-31T18:30:00.000Z\",\n            \"hub\": \"SIN\",\n            \"origin_city\": \"Busan\",\n            \"total_shipments\": \"1\",\n            \"avg_storage_days\": \"20.74\",\n            \"min_storage_days\": \"20.74\",\n            \"max_storage_days\": \"20.74\",\n            \"median_storage_days\": \"20.74\",\n            \"within_week\": \"0\",\n            \"within_two_weeks\": \"0\",\n            \"within_month\": \"1\",\n            \"over_month\": \"0\",\n            \"within_week_percentage\": \"0.00\",\n            \"within_two_weeks_percentage\": \"0.00\",\n            \"storage_days_stddev\": null\n        },\n        {\n            \"month\": \"2025-01-31T18:30:00.000Z\",\n            \"hub\": \"ICN\",\n            \"origin_city\": null,\n            \"total_shipments\": \"418\",\n            \"avg_storage_days\": \"20.47\",\n            \"min_storage_days\": \"4.81\",\n            \"max_storage_days\": \"21.46\",\n            \"median_storage_days\": \"20.46\",\n            \"within_week\": \"1\",\n            \"within_two_weeks\": \"0\",\n            \"within_month\": \"417\",\n            \"over_month\": \"0\",\n            \"within_week_percentage\": \"0.24\",\n            \"within_two_weeks_percentage\": \"0.24\",\n            \"storage_days_stddev\": \"0.80\"\n        },\n        {\n            \"month\": \"2025-01-31T18:30:00.000Z\",\n            \"hub\": \"AMS\",\n            \"origin_city\": null,\n            \"total_shipments\": \"1\",\n            \"avg_storage_days\": \"17.62\",\n            \"min_storage_days\": \"17.62\",\n            \"max_storage_days\": \"17.62\",\n            \"median_storage_days\": \"17.62\",\n            \"within_week\": \"0\",\n            \"within_two_weeks\": \"0\",\n            \"within_month\": \"1\",\n            \"over_month\": \"0\",\n            \"within_week_percentage\": \"0.00\",\n            \"within_two_weeks_percentage\": \"0.00\",\n            \"storage_days_stddev\": null\n        },\n        {\n            \"month\": \"2025-01-31T18:30:00.000Z\",\n            \"hub\": \"RTM\",\n            \"origin_city\": \"Rotterdam\",\n            \"total_shipments\": \"1\",\n            \"avg_storage_days\": \"16.76\",\n            \"min_storage_days\": \"16.76\",\n            \"max_storage_days\": \"16.76\",\n            \"median_storage_days\": \"16.76\",\n            \"within_week\": \"0\",\n            \"within_two_weeks\": \"0\",\n            \"within_month\": \"1\",\n            \"over_month\": \"0\",\n            \"within_week_percentage\": \"0.00\",\n            \"within_two_weeks_percentage\": \"0.00\",\n            \"storage_days_stddev\": null\n        },\n        ...]\n}\n\n```\n\n## //Last mile delivery\n# Last Mile Deliveries SQL Query\n\n## Overview\nThis SQL query calculates key metrics for last-mile deliveries, filtering shipments based on the transport mode and delivery time range.\n\n## Query\n```sql\nWITH last_mile_deliveries AS (\n  SELECT\n    s.id as shipment_id,\n    s.customer,\n    s.origin,\n    s.origin_city,\n    s.destination,\n    s.transport_mode,\n    s.earliest_event_timestamp,\n    s.latest_event_timestamp,\n    EXTRACT(EPOCH FROM (s.latest_event_timestamp - s.earliest_event_timestamp))/3600/24 as delivery_days,\n    s.forwarder\n  FROM shipments s\n  WHERE\n    s.transport_mode = 'local delivery'\n    AND s.earliest_event_timestamp IS NOT NULL\n    AND s.latest_event_timestamp IS NOT NULL\n    AND s.earliest_event_timestamp \u003e= '2025-01-01'\n)\nSELECT\n  customer,\n  forwarder,\n  COUNT(*) as total_deliveries,\n  ROUND(AVG(delivery_days), 1) as avg_delivery_days,\n  ROUND(MIN(delivery_days), 1) as min_delivery_days,\n  ROUND(MAX(delivery_days), 1) as max_delivery_days,\n  ROUND(COUNT(CASE WHEN delivery_days \u003c= 1 THEN 1 END) * 100.0 / COUNT(*), 1) as same_day_delivery_pct,\n  ROUND(COUNT(CASE WHEN delivery_days \u003c= 2 THEN 1 END) * 100.0 / COUNT(*), 1) as within_2days_pct,\n  origin,\n  destination\nFROM last_mile_deliveries\nGROUP BY customer, forwarder, origin, destination\nORDER BY total_deliveries DESC;\n```\n\n## Sample Output\n```json\n{\n    \"success\": true,\n    \"data\": [\n        {\n            \"customer\": \"6549\",\n            \"forwarder\": null,\n            \"total_deliveries\": \"1298\",\n            \"avg_delivery_days\": \"0.6\",\n            \"min_delivery_days\": \"-1.5\",\n            \"max_delivery_days\": \"34.6\",\n            \"same_day_delivery_pct\": \"99.9\",\n            \"within_2days_pct\": \"99.9\",\n            \"origin\": null,\n            \"destination\": \"CNZOS\"\n        },\n        {\n            \"customer\": \"6549\",\n            \"forwarder\": null,\n            \"total_deliveries\": \"432\",\n            \"avg_delivery_days\": \"1.4\",\n            \"min_delivery_days\": \"1.3\",\n            \"max_delivery_days\": \"1.4\",\n            \"same_day_delivery_pct\": \"0.0\",\n            \"within_2days_pct\": \"100.0\",\n            \"origin\": \"ICN\",\n            \"destination\": \"KRPUS\"\n        },\n        {\n            \"customer\": \"60YC\",\n            \"forwarder\": null,\n            \"total_deliveries\": \"19\",\n            \"avg_delivery_days\": \"-10.2\",\n            \"min_delivery_days\": \"-10.4\",\n            \"max_delivery_days\": \"-5.6\",\n            \"same_day_delivery_pct\": \"100.0\",\n            \"within_2days_pct\": \"100.0\",\n            \"origin\": \"JPUKB\",\n            \"destination\": \"JPKII\"\n        }\n    ]\n}\n```\n\n\n![image](https://github.com/user-attachments/assets/cd8fe34a-ad76-40a6-b063-23c7a21f8413)\n\n\n\n//Monthly average duration of storage in days at each hub\nApplies to POs that have departed from the hub within the month.\nDeparture date is calculated as the difference between arrival date and departure from the hub.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fharshproj%2Fnarwal-rqueries","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fharshproj%2Fnarwal-rqueries","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fharshproj%2Fnarwal-rqueries/lists"}