with topfields as (
select concept, sum(n)::int as n, threshold::string as thresh
from all_counts c
where s2fieldsofstudy = ${select_fos}
AND thresh = ${radios}
GROUP BY (concept, thresh)
ORDER BY n DESC
LIMIT ${range}
)
select a.year as date, a.concept, sum(a.n)::int as n, a.threshold::string as thresh, joined
from all_counts a
JOIN topfields b ON a.concept = b.concept
WHERE a.s2fieldsofstudy = ${select_fos}
AND a.threshold = ${radios}
AND date >= 1960
AND date <= 2020
GROUP BY (date, a.concept, a.threshold, joined)
ORDER BY date