Grouped by age first category B lesson

mail@pastecode.io avatar
unknown
mysql
2 years ago
391 B
2
Indexable
Never
SELECT
	TIMESTAMPDIFF(YEAR, birthday, (
			SELECT
				`start` FROM lessons
			WHERE
				student_id = students.id
				AND category = 'B'
			ORDER BY
				`start` ASC
			LIMIT 1)) AS age,
	count(*) AS total
FROM
	students
WHERE
	birthday IS NOT NULL
	AND deleted_at IS NULL
	AND EXISTS (
		SELECT
			*
		FROM
			lessons
		WHERE
			student_id = students.id
			AND category = 'B')
	GROUP BY
		age