mysql中取出每个分组的前80%的数据
思路:
1.把表t_table按照列col1,col2进行排序后,每个分组col2前面增加起始为1,步阶1的序号
2.创建表t_table的按照col2分组后的每个分组的记录总数
3.将上面第1步的子查询和第2步的查询链接,条件为分组列col2=col2并且子查询1的序号<该分组总数的百分比
select a.* from (
SELECT col1, col2,
(CASE col2
WHEN @cur_crew_type
THEN @curRow := @curRow + 1
ELSE @curRow := 0 END) + 1 AS cnt,
@cur_crew_type := col2 AS cur_crew_type
FROM t_table t,
(SELECT @curRow := 0, @cur_crew_type := ‘’) counter
ORDER BY col1, col2
) a join (
select count(1) total, col2 from t_table group by col2) b on a. col2=b.col2 and a.cnt <b.total*0.8