リソース · 68

データ結合の整合性

結合による行の増加が合計値を歪める場合があります。

更新済み · 14 min

白紙のカードを並べた2台の机、真ちゅうのランプ、えんじ色の資料がある架空の無人分析室 AIで生成した編集用イラスト

このガイドが達成するのに役立つこと

  • 行の単位を定義する
  • 結合前に集約する
  • 対応しない行を調べる

クイックチェック

  • 一行の意味を定義し、結合前後のキー、件数、合計を照合します。
  • 重複削除だけでは誤った関係を隠すことがあります。

手順

  1. 1

    行の単位を定義する

    注文テーブルの1行は注文、明細の1行は注文内の商品を表します。結合前に重複キーとNULLキーを確認します。

    各テーブルの行の単位とキーを記録します。

  2. 2

    結合前に集約する

    明細を注文キーごとに集約します。その結果と結合すれば、商品ごとに注文金額が繰り返されません。元の注文テーブルの合計と照合します。

    両方のクエリと合計を保存します。

  3. 3

    対応しない行を調べる

    LEFT JOINは明細のない注文を残しますが、右側テーブルへのWHERE条件はその注文を除外する場合があります。対応する行がないことと金額ゼロは別です。

    除外した注文とフィルター条件を記録します。

再現できる受け入れ事例

架空の例です。顧客や実際の観測結果を示すデータではありません。

事例の入力を見る
{
    "orders": [
        {
            "id": 1,
            "total": 100
        },
        {
            "id": 2,
            "total": 200
        }
    ],
    "line_order_ids": [
        1,
        1,
        2
    ],
    "sum_before": 300,
    "sum_after_raw_join": 400
}

期待される判断

400は注文を二重計上しています。注文ごとに明細を集約し、合計300に戻します。 追加で、各100の架空の注文を2件試します。合計は200です。SUM(DISTINCT total)では100となり、正しい値が消えます。金額の重複排除ではなく、識別子と結合の対応件数を確認します。

再現できるSQLクエリ

架空例:金額100と200の注文2件と、注文1、1、2に対応する明細3件。クエリはVALUESだけを使います。テスト環境で実行してください。

WITH orders(id, total) AS (VALUES (1, 100), (2, 200)),
lines(order_id) AS (VALUES (1), (1), (2))
SELECT COUNT(*) AS rows, SUM(o.total) AS total
FROM orders o JOIN lines l ON l.order_id = o.id;
WITH orders(id, total) AS (VALUES (1, 100), (2, 200)),
lines(order_id) AS (VALUES (1), (1), (2)),
per_order AS (
  SELECT order_id, COUNT(*) AS line_count
  FROM lines GROUP BY order_id
)
SELECT COUNT(*) AS orders, SUM(o.total) AS total
FROM orders o LEFT JOIN per_order l ON l.order_id = o.id;

直接結合すると3行で合計400になります。先に集約すれば2件の注文と合計300を得られます。

WITH orders(id, total) AS (VALUES (1, 100), (2, 100))
SELECT SUM(total) AS correct_total,
       SUM(DISTINCT total) AS distinct_total
FROM orders;

金額が100と100の場合、正しい合計は200ですがSUM(DISTINCT total)は100です。

検証手順

  1. 注文と明細の粒度を定めます。
  2. 2明細の注文を結合します。
  3. キー、件数、照合済み合計を残します。

PostgreSQL — Table expressions and joins

メカニズムの区別

メカニズム目的検証または制限
INNER JOIN一致する行を残す明細のない注文を除外する
LEFT JOIN左側の注文をすべて残す後続のフィルターで除外される場合がある
SUM(DISTINCT total)同じ金額を除外する異なる注文でも同額の場合がある

管理指標

指標測定対象最初のアクション
COUNT(*)注文テーブルの1行は注文、明細の1行は注文内の商品を表します。結合前に重複キーとNULLキーを確認します。各テーブルの行の単位とキーを記録します。
SUM(total)明細を注文キーごとに集約します。その結果と結合すれば、商品ごとに注文金額が繰り返されません。元の注文テーブルの合計と照合します。両方のクエリと合計を保存します。

よくある間違い

  • 明細のない注文を除外する
  • 後続のフィルターで除外される場合がある
  • 異なる注文でも同額の場合がある

よくある質問

SUM(DISTINCT total)だけで直せますか?

いいえ。100の注文が2件あれば合計は200ですが、SUM(DISTINCT total)は100になります。金額の重複排除ではなく、キーの関係を修正します。

結合の多重度、NULL、集計

この言語版の詳しい参照メモは英語で提供しています。

A join transforms a set of rows before metrics are computed. To investigate a difference, inspect the resulting pairs and removed records: comparing two sums is insufficient. This workshop follows two fictional sources through to six aggregates without connecting to a database.

Documentary reference: PostgreSQL 18, chapters 7.2, 9.2 and 9.21, reviewed on 23 October 2026. Data, scenarios and acceptance suggestions are original CIE examples. They describe no real company, person or observed performance.

PostgreSQL 18 · Table expressions · PostgreSQL 18 · documentation reviewed 2026-10-23

Four reference points for reading a join

Four reference points for reading a join
Reference pointDocumented SQL effectAcceptance question
Pairs and cardinalityEach true match produces a pair; LEFT null-extends left rows with no match.How many right rows match each left identifier?
ON and WHEREON decides matches before LEFT extension; WHERE then retains only rows with a true predicate.Does the filter define the relationship or final population?
NULL keysOrdinary equality with NULL yields unknown. IS NOT DISTINCT FROM treats two nulls as not distinct.Does matching two missing values make business sense?
AggregatesCOUNT(*) counts rows; COUNT(expression) counts non-null values; SUM ignores null values.What is the contribution grain and what does a missing value mean?

PostgreSQL 18 · Comparison functions · PostgreSQL 18 · documentation reviewed 2026-10-23

Two fictional six-row sources

Each left row is an independent technical record identified by l.id; metric is an integer quantity with no business unit. A right row is a state associated with a key. Key A repeats on both sides; row identifiers are unique and non-null. NULL denotes a missing value, never the text “NULL”. L4’s zero is a present measurement. Left baseline: 6 rows, 5 non-null measurements and SUM(metric) = 430; one measurement is unknown, so this is not a complete total of every quantity.

Left source lab_left
l.idl.keyl.metric
L1A100
L2A200
L3B50
L4C0
L5NULL80
L6DNULL
Right source lab_right
r.idr.keyr.state
R1Aactive
R2Ainactive
R3Bactive
R4NULLactive
R5Eactive
R6DNULL

行照合ワークショップ

Choose INNER or LEFT, the position of r.state = 'active', key comparison and a full or empty right source. The 24 configurations are bounded to these data. The result table shows each pair and null-extended rows. Six aggregates apply to the result after any WHERE filter.

This local reader executes no SQL, collects no data and offers no import or export. It covers no collations, type conversion, composite keys, temporal joins, permissions, performance or other SQL dialects. Identifier ordering is added for readability; a join alone does not guarantee this order.

Keep the left reference of 430 over five known measurements for comparison. An unchanged sum after joining does not establish matching quality: duplication and exclusion may offset each other.

What the six results actually count

What the six results actually count
ExpressionReading in this exercise
COUNT(*)All final rows, including null-extended LEFT rows.
COUNT(DISTINCT l.id)Distinct retained left identifiers. This count does not repair a repeated sum.
COUNT(r.id)Rows with an actual right record: source r.id is always non-null.
COUNT(r.key)Non-null right keys. May be below COUNT(r.id) when a null-key record matched.
COUNT(l.metric)Occurrences of non-null left measurements, including repetitions; zero counts as present.
SUM(l.metric)Sum of non-null values after joining. NULL when no non-null value contributes, including an empty result.

PostgreSQL 18 · Aggregate functions · PostgreSQL 18 · documentation reviewed 2026-10-23

Nine explained scenarios, available without JavaScript

J01 · LEFT with repeated key A
LEFT with repeated key A
Join / filter / keys / right sourceExpected reading
LEFT / none / equal / full8 rows, 6 left identifiers, 6 present r.id, 6 present r.key, 7 present measurements; sum 730. A produces four pairs.
J02 · INNER and removed records
INNER and removed records
Join / filter / keys / right sourceExpected reading
INNER / none / equal / full6 rows, 4 left identifiers, 5 measurements; sum 650. L4 and L5 disappear; A duplication remains.
J03 · Active filter in ON
Active filter in ON
Join / filter / keys / right sourceExpected reading
LEFT / on / equal / full6 rows and 6 left identifiers; 3 present r.id, 5 measurements; sum 430. L4, L5 and L6 retain null-extended right values.
J04 · Same filter in WHERE
Same filter in WHERE
Join / filter / keys / right sourceExpected reading
LEFT / where / equal / full3 rows and 3 left identifiers; sum 350. The filter removes rows without active state, including null-extended rows.
J05 · Two null keys matched
Two null keys matched
Join / filter / keys / right sourceExpected reading
LEFT / none / safe / full8 rows, 7 present r.id but 6 present r.key; sum 730. L5 actually matches R4; null r.key therefore does not establish an unmatched row.
J06 · Misleading equal sum
Misleading equal sum
Join / filter / keys / right sourceExpected reading
INNER / where / safe / full4 rows, 4 left identifiers and sum 430: same sum as the baseline, although L4 and L6 are absent. Equal totals do not mean equal populations.
J07 · Empty result and null sum
Empty result and null sum
Join / filter / keys / right sourceExpected reading
INNER / none / equal / emptyNo rows. All five COUNT values are 0; SUM(l.metric) is NULL. The reader does not replace this absence with zero.
J08 · Empty right, preserved left
Empty right, preserved left
Join / filter / keys / right sourceExpected reading
LEFT / none / equal / empty6 rows, 6 left identifiers, no present r.id or r.key; 5 measurements and sum 430. Left values remain present.
J09 · WHERE removes every extended row
WHERE removes every extended row
Join / filter / keys / right sourceExpected reading
LEFT / where / equal / emptyLEFT first produces six extended rows; the active WHERE predicate removes all of them. Five COUNT values 0, sum NULL.

Prepare evidence for a reliable reconciliation

Prepare evidence for a reliable reconciliation
Suggested checkUseful record
Grain and keysDescribe one row in each source, its identifiers and expected business cardinality. Repeated keys may be legitimate.
Scope and stateFix period, time zone, source versions and relevant state date before joining.
MatchesList records with zero, one or several matches; retain identifiers from both sides.
Missing valuesSeparate null key, null measurement, null state and absent right record. Do not replace all four with zero.
AggregationCompare at the business grain before and after joining. Document any allocation rule and reconcile its result.
RegressionKeep repeated keys, null keys, zero, unknown measurement and empty-source cases; check rows as well as totals.

In this exercise two left A rows and two right A rows produce four pairs without a filter. Removing a right row or applying DISTINCT without understanding its role can lose valid information. Choose prior aggregation, a more precise key or an allocation rule only after defining the business need.

Sources, edition and credits

Official PostgreSQL Global Development Group documentation, edition 18. Original CIE summary, fictional data and educational reader; no PostgreSQL engine or code is embedded. References describe the selected semantics and do not certify this reader.

PostgreSQL 18 · Table expressions · PostgreSQL 18 · documentation reviewed 2026-10-23

SHA-256 : 252f02babbaec8ac702ff2966db75d0b38886cb576a90bbfc458bc4abd0dc688

PostgreSQL 18 · Aggregate functions · PostgreSQL 18 · documentation reviewed 2026-10-23

SHA-256 : c466d05fe796e77f1362dae39c8b212c7bf381065904eb555fa91537e363e5d0

PostgreSQL 18 · Comparison functions · PostgreSQL 18 · documentation reviewed 2026-10-23

SHA-256 : f08404f5624f8b87a91f117be7d59feca075508b124552b66b61940b5b6ef28c

公式参照文献

参照文献はメソッドを裏付けるものです。 チェックは状況に合わせて調整してください。 これらは認証ではありません。 元の参照文献のタイトルやソース文書は別の言語で書かれている場合があります。

参照資料の確認日 .