You need a LEFT JOIN
against a subquery for each levN
column, which returns the distinct level, and count for that column. They all then get added up and joined to user_id
.
SELECT
DISTINCT
user_id,
/* COALESCE() is needed so NULLs don't ruin the calculation */
COALESCE(l1count, 0) +
COALESCE(l2count, 0) +
COALESCE(l3count, 0) +
COALESCE(l4count, 0) AS children
FROM
yourtable
/* a left join individually against each of the `levN` columns to get the count per value of each */
LEFT JOIN (SELECT lev1, COUNT(*) AS l1count FROM yourtable GROUP BY lev1) l1 ON yourtable.user_id = l1.lev1
LEFT JOIN (SELECT lev2, COUNT(*) AS l2count FROM yourtable GROUP BY lev2) l2 ON yourtable.user_id = l2.lev2
LEFT JOIN (SELECT lev3, COUNT(*) AS l3count FROM yourtable GROUP BY lev3) l3 ON yourtable.user_id = l3.lev3
LEFT JOIN (SELECT lev4, COUNT(*) AS l4count FROM yourtable GROUP BY lev4) l4 ON yourtable.user_id = l4.lev4