Progressive Tier CASE Pricing
CASE maps each weight to its tier rate and charges only the portion inside that band, avoiding the full-amount-at-top-tier mistake.
Code
-- 阶梯计价 (progressive tier pricing):CASE 把重量映射到档位费率,只对该段重量计费
CREATE TABLE waybills (
waybill_id int PRIMARY KEY,
weight_kg numeric NOT NULL
);
INSERT INTO waybills VALUES (1, 3.0), (2, 8.0), (3, 12.5);
-- 首重 3kg 固定 15 元;3-10kg 部分每 kg 4 元;超过 10kg 部分每 kg 2.5 元
SELECT
waybill_id,
weight_kg,
15.00 + CASE
WHEN weight_kg > 10 THEN 4.00 * 7 + 2.50 * (weight_kg - 10)
WHEN weight_kg > 3 THEN 4.00 * (weight_kg - 3)
ELSE 0
END AS shipping_charge
FROM waybills
ORDER BY waybill_id;
DROP TABLE waybills;How the snippet works
What runs here is SELECT / INSERT / CREATE — waybills are the objects involved.
Mechanically, the statements are built from: an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Applying it
The waybills table is the working surface here.
Statements that matter
SELECT
waybill_id,
weight_kg,
15.00 + CASE
WHEN weight_kg > 10 THEN 4.00 * 7 + 2.50 * (weight_kg - 10)
WHEN weight_kg > 3 THEN 4.00 * (weight_kg - 3)
ELSE 0
END AS shipping_charge
FROM waybills
ORDER BY waybill_id;
CREATE TABLE waybills (
waybill_id int PRIMARY KEY,
weight_kg numeric NOT NULL
);
INSERT INTO waybills VALUES (1, 3.0), (2, 8.0), (3, 12.5);
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 are the relations in play here?
- The references are `waybills`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.