WITH RECURSIVE `subs` (`name`, `value`, `order`) AS (
SELECT CONCAT('{{> ', `p`.`name`, '}}'), `p`.`value`, ROW_NUMBER() OVER ()
FROM `templates` AS `t`
JOIN `parts` AS `p`
ON `t`.`value` LIKE CONCAT('%{{> ', `p`.`name`, '}}%')
WHERE `t`.`id` = 1
),
`result` (`value`, `order`) AS (
SELECT `value`, 0
FROM `templates`
WHERE `id` = 1
UNION SELECT REPLACE(`r`.`value`, `s`.`name`, `s`.`value`), `s`.`order`
FROM `result` AS `r`
JOIN `subs` AS `s`
ON `s`.`order` = `r`.`order` + 1
)
SELECT `value`
FROM `result`
ORDER BY `order` DESC
LIMIT 1
SELECT PeopleTable.gender, COUNT(*) AS GenderCount
FROM ListTable
INNER JOIN PeopleTable ON ListTable.userID = PeopleTable.id
GROUP BY PeopleTable.gender
ListTable
, у которых нет соответствия в PeopleTable
SELECT ISNULL(PeopleTable.gender, '-') [Пол], COUNT(*) [К-во]
FROM ListTable
LEFT JOIN PeopleTable ON ListTable.userID = PeopleTable.id
GROUP BY ROLLUP (PeopleTable.gender)
UNION
SELECT ' ', COUNT(*)
FROM ListTable
ORDER BY 1 DESC, 2
DBCC CHECKTABLE ('PeopleTable')
DBCC CHECKTABLE ('ListTable')
SELECT
COUNT(DISTINCT CASE WHEN people.gender = 'M' THEN list.id END) AS mens,
COUNT(DISTINCT CASE WHEN people.gender = 'F' THEN list.id END) AS womens,
COUNT(DISTINCT CASE WHEN people.gender IS NULL THEN list.id END) AS unknown
FROM ListTable AS list
LEFT JOIN PeopleTable AS people ON (list.userID = people.id)
;