2013-06-11 58 views
2

我有一個簡單的MySQL數據庫,列出了每個用戶每天花在網上的總時間(僅僅是一個字符串)。我想選擇這些用戶中前10%的用戶,並返回用戶名。MySQL選擇前10%的用戶

有沒有辦法在單個查詢中在MySQL中執行此操作..?我在哪裏見過你選擇最上面的10個用戶的例子,但不是基於用戶總數的百分比...

+0

http://stackoverflow.com/questions/4741239/select-top-x-or-bottom-percent-for-numeric-values-in -mysql – Ryan

+0

將時間字符串重構爲整數值;然後使用ORDER BY和LIMIT – mcm

回答

0

希望這將幫助你

我用CURRENT_DATE限制搜索。

SELECT user_id, date, total_time FROM 
(
    SELECT user_id, @rownum:[email protected]+1 AS rownum 
    FROM TABLE_USER , (SELECT @rownum:=0) R 
    WHERE date = CURRENT_DATE 
    ORDER by total_time desc 
) temp 
where rownum < (select count(*) from TABLE_USER where date = CURRENT_DATE)/10 
+0

這似乎不工作,我只是得到一個_mysql_exceptions.OperationalError:(1054,「未知列'user_id'在'字段列表')錯誤,儘管列在db中 – DavidJB

+0

你能給我表的創建腳本! – agarici

0

試試這個

 SELECT 0.1 * count(username) as percented_users FROM prices 
    GROUP BY username 
+0

這僅返回0.1 *用戶總數。我需要前10% – DavidJB

0

你可以試試這樣:

select * from table limit floor((select count(1) from table)*0.1)