我需要根据百分比限制记录,但MYSQL不允许这样做。我需要10%User Id
(count(
用户ID )/max(Total_Users_bynow)
我的代码如下:
select * from flavia.TableforThe_top_10percent_of_the_user where `User Id` in (select distinct(`User Id`) from flavia.TableforThe_top_10percent_of_the_user group by `User Id` having count(distinct(`User Id`)) <= round((count(`User Id`)/max(Total_Users_bynow))*0.1)*count(`User Id`));
请帮助。
答案 0 :(得分:1)
考虑将问题分成几部分。您可以使用用户变量来获取所需内容。 Quoting from this question's answers:
您不必在单个查询中解决所有问题。
所以......让我们完成这件事。我不会提出您的完整查询,但有些例子:
-- Step 1. Get the total of the rows of your dataset
set @nrows = (select count(*) from (select ...) as a);
-- --------------------------------------^^^^^^^^^^
-- The full original query (or, if possible a simple version of it) goes here
-- Step 2. Calculate how many rows you want to retreive
-- You may use "round()", "ceiling()" or "floor()", whichever fits your needs
set @limrows = round(@nrows * 0.1);
-- Step 3. Run your query:
select ...
limit @limrows;
击> <击> 撞击>
检查后,我发现this post表示上述方法无法正常工作。但是,还有另一种选择:
-- Step 1. Get the total of the rows of your dataset
set @nrows = (select count(*) from (select ...) as a);
-- --------------------------------------^^^^^^^^^^
-- The full original query (or, if possible a simple version of it) goes here
-- Step 2. Calculate how many rows you want to retreive
-- You may use "round()", "ceiling()" or "floor()", whichever fits your needs
set @limrows = round(@nrows * 0.1);
-- Step 3. (UPDATED) Run your query.
-- You'll need to add a "rownumber" column to make this work.
select *
from (select @rownum := @rownum+1 as rownumber
, ... -- The rest of your columns
from (select @rownum := 0) as init
, ... -- The rest of your FROM definition
order by ... -- Be sure to order your data
) as a
where rownumber <= @limrows
希望这会有所帮助(我认为这次没有怪癖会有效)