← 中文资源

简体中文版本

用 CASE 映射财年

财年从 7 月起算:CASE 按月份映射财年,CTE 派生 FY 标签后按财年汇总订单数与收入,1-6 月的订单自动归入上一年度。

阅读英文原文

实现说明

这个文件依次执行 SELECT / INSERT / CREATE 语句,涉及 orders、ordered_on、tagged。 语句实际拼装出的结构:先用 WITH … AS 把中间结果命名成 CTE,主查询再引用它;用 COUNT、SUM 做聚合;GROUP BY 把同组行折叠成每个分组一行;ORDER BY 固定了输出顺序;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY。

常见问题

这段 SQL 涉及哪些对象?

orders、ordered_on、tagged——直接引用,无需连接。

核心语句

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
);

代码示例

-- 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;