WITH uma_names AS (
	SELECT
		"index" AS "id",
		"text" AS "name"
	FROM text_data
	WHERE category = 6 AND "index" BETWEEN 1000 AND 1999
	-- Exclude characters who have no succession relations defined.
	AND "index" IN (SELECT chara_id FROM succession_relation_member)
), trios AS (
	SELECT
		a.id AS id_a,
		a.name AS name_a,
		b.id AS id_b,
		b.name AS name_b,
		c.id AS id_c,
		c.name AS name_c,
		ra.relation_type
	FROM uma_names a
		JOIN uma_names b ON a.id != b.id
		JOIN uma_names c ON a.id != c.id AND b.id != c.id
		JOIN succession_relation_member ra ON a.id = ra.chara_id
		JOIN succession_relation_member rb ON b.id = rb.chara_id
		JOIN succession_relation_member rc ON c.id = rc.chara_id
	WHERE
		ra.relation_type = rb.relation_type
		AND ra.relation_type = rc.relation_type
), affinity AS (
	SELECT
		id_a,
		name_a,
		id_b,
		name_b,
		id_c,
		name_c,
		SUM(relation_point) AS base_affinity
	FROM trios
		JOIN succession_relation sr ON trios.relation_type = sr.relation_type
	GROUP BY id_a, id_b, id_c
)
SELECT * FROM affinity
ORDER BY id_a, id_b, id_c