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.

  1. is possible in single query? how?

  2. 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 

sql fiddle demo


Comments

Popular posts from this blog

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -

java - JavaFX 2 slider labelFormatter not being used -