WITH saddle_names AS (
	SELECT "index" AS id, "text" AS name
	FROM text_data
	WHERE category = 111
)
SELECT
	s.id,
	n.name,
	ri1.id AS race1,
	IFNULL(ri2.id, 0) AS race2,
	IFNULL(ri3.id, 0) AS race3,
	s.win_saddle_type,
	MIN(s.id) OVER (PARTITION BY n.name) AS "primary",
	ROW_NUMBER() OVER (PARTITION BY n.name ORDER BY s.id) - 1 AS "alternate"
FROM single_mode_wins_saddle s
	JOIN race_instance ri1 ON s.race_instance_id_1 = ri1.id
	LEFT JOIN race_instance ri2 ON s.race_instance_id_2 = ri2.id
	LEFT JOIN race_instance ri3 ON s.race_instance_id_3 = ri3.id
	LEFT JOIN saddle_names n ON s.id = n.id
ORDER BY s.id
