SUM DISTINCT Versus Dedup First
SUM(DISTINCT x) collapses equal values inside one aggregate, which silently shrinks totals when legitimate duplicates exist; dedup a known key instead.
Code
-- SUM(DISTINCT x):先在同一分区内去重再求和,重复值只计一次
WITH metrics(device, reading) AS (
VALUES
('a1', 10),
('a1', 10), -- 重传导致的重复读数
('a1', 20),
('b2', 5)
)
SELECT
device,
SUM(reading) AS sum_all, -- a1 = 40:重复合计进来
SUM(DISTINCT reading) AS sum_distinct, -- a1 = 30:两个 10 只算一个
COUNT(reading) AS row_count,
COUNT(DISTINCT reading) AS distinct_count
FROM metrics
GROUP BY device
ORDER BY device;
-- 危险点:两条金额都为 100 的订单在 SUM(DISTINCT) 下只算一次,总额静默偏小。
-- 真正的"按业务键去重"要先 SELECT DISTINCT 子查询,再对去重结果聚合。
WITH orders(order_id, cents) AS (
VALUES (1, 100), (2, 100), (3, 250)
),
deduped AS (
SELECT DISTINCT order_id, cents FROM orders
)
SELECT SUM(cents) AS deduped_total FROM deduped; -- 450,而不是 SUM(DISTINCT) 的 350How the logic unfolds
What runs here is SELECT — metrics, orders and deduped are the objects involved.
The SQL constructs in play: 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; a DISTINCT qualifier that collapses duplicate rows.
Applying it
Point it at the metrics table.
Statements that matter
WITH orders(order_id, cents) AS (
VALUES (1, 100), (2, 100), (3, 250)
),
deduped AS (
SELECT DISTINCT order_id, cents FROM orders
)
SELECT SUM(cents) AS deduped_total FROM deduped; -- 450,而不是 SUM(DISTINCT) 的 350
Interactive Tools for This Topic
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.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.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.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables appear in this script?
- `metrics`, `orders`, `deduped` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.