2009-08-11 26 views
2

我们有一个DB存储可能有图片的用户。SQL:选择n%带图片,(100-n)%不带图片

我在寻找一个优雅的方式在SQL中得到以下结果: 选择n个用户。在这n个用户中,例如60%应该有相关图片,40%不应该有图片。如果有少于60%的用户拥有图片,则结果应该由没有图片的用户填写。

SQL中有没有触发多个SELECT到数据库的优雅方式?

非常感谢。

回答

0

丑陋的代码:

SELECT TOP @n * FROM 
(


     //-- We start selecting users who have a picture (ordered by HasPicture) 
     //-- If there is no more users with a picture, this query will fill the 
     //-- remaining rows with users without a picture 
     SELECT TOP 60 PERCENT * FROM tbUser 
     ORDER BY HasPicture DESC 

     UNION 

     //-- This is to make sure that we select at least 40% users without a picture 
     //-- AT LEAST because in the first query it is possible that users without a 
     //-- picture have been selected 
     SELECT TOP 40 PERCENT * FROM tblUser 
     WHERE HasPicture = 0 

     //-- We need to avoid duplicates because in the first select query we haven't 
     //-- specified HasPicture = 1 (and we didn't want to). 
     AND UserID not IN 
     (
     SELECT TOP 60 PERCENT UserID FROM tbUser 
     ORDER BY HavePicture DESC 
    ) 
) 
+0

-1 Huh?你没有限制N的整体,告诉谁有图片,谁没有图片的代码是没有意义的。 – 2009-08-11 17:40:13

+0

我添加了一些评论,所以我想它现在变得更有意义了......我同意这不是最优雅的一段代码,但我认为它工作正常。我个人比较喜欢Rob的解决方案。 – Max 2009-08-12 07:36:45

+0

谢谢Max。如果你喜欢,你可以把它标记为答案。我觉得我的个人资料还没有很多被接受的答案。我的大部分声誉来自于我第一次加入该网站时发布的一个答案。 – 2009-08-12 08:13:59

0
SELECT TOP(n) HasPicture --should be 0 or 1 to allow ORDER 
    FROM Users 
    ORDER BY 1 
2

所以你提供@n,是你想要的用户数。 您提供的@x是应该有图片的用户的百分比。

select top (@n) * 
from 
(
select top (@n * @x/100) * 
from users 
where picture is not null 

union all 

select top (@n) * 
from users 
where picture is null 
) u 
order by case when picture is not null then 1 else 2 end; 

所以...你想在谁拥有最多的图片@n * @x/100用户,其余的必须是没有照片的人谁。所以我在我的@ n * @ x/100图片人员和足够的其他人员之间做了一个'union all'来完成我的@n。然后我选择他们,订购我的TOP,以确保我保留有照片的人。

罗布

编辑:其实,这会更好:

select top (@n) * 
from 
(
select top (@n * @x/100) *, 0 as NoPicture 
from users 
where picture is not null 

union all 

select top (@n) *, 1 as NoPicture 
from users 
where picture is null 
) u 
order by NoPicture; 

...因为它消除了ORDER BY的影响。

+0

但是......如果没有足够的人没有图片,你需要填写(100-x)%的图片人吗? – 2009-08-11 08:46:55

+0

hm no。这不会成为一项要求,因为没有照片的人数会更多。 – Max 2009-08-11 09:02:38

+0

好的,很酷。那么,仔细阅读所有的选项,确保你了解每个场景正在做什么,并选择最符合你的要求的东西(我不确定这些东西是否特别清楚)。 – 2009-08-11 09:05:39

0

对此类需求使用Select大小写。