sql - How to select different percentages of data based in a column value? -
i need query table have "gender" column, so:
| id | gender | name | ------------------------- | 1 | m | michael | ------------------------- | 2 | f | hanna | ------------------------- | 3 | m | louie | -------------------------
and need extract first n results have, example 80% males , 20% females. so, if needed 1000 results want retrieve 800 males , 200 females.
is possible in single query? how?
if don't have enough records (imagine have 700 males on example above) possible select 700 / 300 automatically?
basically, want many 'm' can, not more percentage , enough 'f' have total 1000 rows:
with cte_m ( select * table1 gender = 'm' limit (1000 * 0.8) ), cte ( select *, 0 ord cte_m union select *, 1 ord table1 gender = 'f' order ord limit 1000 ) select id, gender, name cte
Comments
Post a Comment