我们有一个数据库来存储可能有图片的用户。
我正在寻找一种优雅的 SQL 方法来获得以下结果:选择 n 个用户。在这 n 个用户中,例如 60% 的用户应该有相关的图片,而 40% 的用户不应该有图片。如果少于 60% 的用户有图片,则结果应该由没有图片的用户填充。
在 SQL 中是否有一些优雅的方式,而无需向数据库触发多个 SELECT?
非常感谢你。
我们有一个数据库来存储可能有图片的用户。
我正在寻找一种优雅的 SQL 方法来获得以下结果:选择 n 个用户。在这 n 个用户中,例如 60% 的用户应该有相关的图片,而 40% 的用户不应该有图片。如果少于 60% 的用户有图片,则结果应该由没有图片的用户填充。
在 SQL 中是否有一些优雅的方式,而无需向数据库触发多个 SELECT?
非常感谢你。
因此,您提供@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 的影响。
SELECT TOP(n) HasPicture --should be 0 or 1 to allow ORDER
FROM Users
ORDER BY 1
丑陋的代码:
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
)
)
对此类需求使用 Select 案例。