SQL:用图片选择n%,没有图片的(100-n)%

时间:2009-08-11 07:56:28

标签: sql-server union

我们有一个DB,用于存储可能有图片的用户。

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

在SQL中是否有一些优雅的方法而不向DB发送多个SELECT?

非常感谢。

4 个答案:

答案 0 :(得分: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图片人和其他人之间进行“联合所有”以完成我的@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的影响。

答案 1 :(得分:0)

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

答案 2 :(得分: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
      )
 )

答案 3 :(得分:0)

对此类要求使用选择案例。