WITH skill_names AS (
	SELECT
		n."index" AS "id",
		n."text" AS "name",
		d."text" AS "description"
	FROM text_data n
		JOIN text_data d ON n."index" = d."index" AND n."category" = 47 AND d."category" = 48
), skill_groups AS (
	SELECT
		group_id,
		name
	FROM skill_data d
		JOIN skill_names n ON d.id = n.id
	WHERE group_rate = 1
), card_name AS (
	SELECT
		"index" AS "id",
		"text" AS "name"
	FROM text_data n
	WHERE category = 4
), card_unique AS (
	SELECT DISTINCT
		ss.skill_id1 AS unique_id,
		card_name.id AS owner_id,
		card_name.name
	FROM card_data card
		JOIN card_name ON card.id = card_name.id
		JOIN card_rarity_data rd ON card.id = rd.card_id
		JOIN skill_set ss ON rd.skill_set = ss.id
)
SELECT
	d.id,
	n.name,
	n.description,
	IIF(d.unique_skill_id_1 = 0, d.group_id, ud.group_id) AS group_id,
	CASE
		WHEN g.name IS NOT NULL THEN g.name
		WHEN d.unique_skill_id_1 != 0 THEN n.name
		ELSE ''
	END AS group_name,
	d.rarity,
	d.group_rate,
	d.grade_value,
	d.activate_lot,
	d.precondition_1,
	d.condition_1,
	d.float_ability_time_1,
	d.ability_time_usage_1,
	d.float_cooldown_time_1,
	d.ability_type_1_1,
	d.ability_value_usage_1_1,
	d.float_ability_value_1_1,
	d.target_type_1_1,
	d.target_value_1_1,
	d.ability_type_1_2,
	d.ability_value_usage_1_2,
	d.float_ability_value_1_2,
	d.target_type_1_2,
	d.target_value_1_2,
	d.ability_type_1_3,
	d.ability_value_usage_1_3,
	d.float_ability_value_1_3,
	d.target_type_1_3,
	d.target_value_1_3,
	d.precondition_2,
	d.condition_2,
	d.float_ability_time_2,
	d.ability_time_usage_2,
	d.float_cooldown_time_2,
	d.ability_type_2_1,
	d.ability_value_usage_2_1,
	d.float_ability_value_2_1,
	d.target_type_2_1,
	d.target_value_2_1,
	d.ability_type_2_2,
	d.ability_value_usage_2_2,
	d.float_ability_value_2_2,
	d.target_type_2_2,
	d.target_value_2_2,
	d.ability_type_2_3,
	d.ability_value_usage_2_3,
	d.float_ability_value_2_3,
	d.target_type_2_3,
	d.target_value_2_3,
	IFNULL(p.need_skill_point, 0) AS sp_cost,
	d.unique_skill_id_1,
	COALESCE(u.owner_id, iu.owner_id, 0) AS unique_owner_id,
	COALESCE(u.name, iu.name, '') AS unique_owner,
	d.icon_id,
	d.tag_id
FROM skill_data d
	JOIN skill_names n ON d.id = n.id
	LEFT JOIN skill_data ud ON d.unique_skill_id_1 = ud.id
	LEFT JOIN skill_groups g ON d.group_id = g.group_id
	LEFT JOIN single_mode_skill_need_point p ON d.id = p.id
	LEFT JOIN card_unique u ON d.id = u.unique_id
	LEFT JOIN card_unique iu ON d.unique_skill_id_1 = iu.unique_id
ORDER BY d.id
