Fiscal Year Mapping With CASE
Map each order to a July-start fiscal year with CASE on the month, then roll orders and revenue up per fiscal year through a CTE.
Code
-- the fiscal year starts July 1: months 7-12 belong to the current year, months 1-6 to the previous one
CREATE TABLE orders (
order_id int PRIMARY KEY,
ordered_on date NOT NULL,
amount_cents bigint NOT NULL
);
INSERT INTO orders (order_id, ordered_on, amount_cents) VALUES
(1, DATE '2025-08-14', 12000),
(2, DATE '2025-12-31', 8000),
(3, DATE '2026-03-02', 9500),
(4, DATE '2026-06-30', 4000),
(5, DATE '2026-07-01', 15000);
WITH tagged AS (
SELECT
order_id,
ordered_on,
amount_cents,
-- fiscal-year mapping: months 7-12 stay in the current year, 1-6 fall back one year
CASE
WHEN EXTRACT(MONTH FROM ordered_on) >= 7 THEN EXTRACT(YEAR FROM ordered_on)::int
ELSE EXTRACT(YEAR FROM ordered_on)::int - 1
END AS fiscal_year
FROM orders
)
SELECT
fiscal_year,
'FY' || fiscal_year AS fiscal_label,
COUNT(*) AS orders,
SUM(amount_cents) / 100.0 AS revenue
FROM tagged
GROUP BY fiscal_year
ORDER BY fiscal_year;How it works
The file runs SELECT / INSERT / CREATE statements, touching orders, ordered_on and tagged.
Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; COUNT, SUM aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Putting it to use
The orders table is the working surface here.
Core lines
INSERT INTO orders (order_id, ordered_on, amount_cents) VALUES
(1, DATE '2025-08-14', 12000),
(2, DATE '2025-12-31', 8000),
(3, DATE '2026-03-02', 9500),
(4, DATE '2026-06-30', 4000),
(5, DATE '2026-07-01', 15000);
CREATE TABLE orders (
order_id int PRIMARY KEY,
ordered_on date NOT NULL,
amount_cents bigint NOT NULL
);
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Case ConverterConvert text between lowercase, uppercase, title, sentence, camelCase, snake_case, and kebab-case while preserving Unicode letters and numbers.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- What objects does the SQL involve?
- `orders`, `ordered_on`, `tagged` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.