需求:mysql分組排序,1、取最大(小)前N位,2、取中位數
本例以shop_id和cat_id字段共同分組,並對最細粒度的分組cat_id降序排列
原始表:
2、mysql分組排序(含組內排名)
SELECT a.shop_id,a.cat_id, a.price, count(*) as rank
FROM mygoods a
JOIN mygoods b ON a.shop_id=b.shop_id and a.cat_id = b.cat_id AND a.price <= b.price
GROUP BY a.shop_id,a.cat_id, a.price
ORDER BY a.shop_id,a.cat_id asc,a.price desc
;
如果要求中位數,在上面的基礎上,用以下語句進行篩選:
WHERE Rank = (SELECT (COUNT(*)+1) DIV 2 FROM Table_Name);
注意:上述可根據情況把JOIN 改成 LEFT JOIN
3、結果數據
注意:轉載請保留原文鏈接 http://www.cnblogs.com/merru/articles/4626045.html