2

写真を持っている可能性のあるユーザーを保存するDBがあります。

次の結果を得るために SQL で洗練された方法を探しています: n ユーザーを選択します。これらの n ユーザーのうち、たとえば 60% は関連付けられた画像を持ち、40% は画像を持たない必要があります。写真を持っているユーザーが 60% 未満の場合、結果は画像のないユーザーでいっぱいになるはずです。

DB に対して複数の SELECT を実行することなく、SQL に洗練された方法はありますか?

どうもありがとうございました。

4

4 に答える 4

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;

...それはORDERBYの影響を取り除くからです。

于 2009-08-11T08:45:19.390 に答える
0

このタイプの要件には Select ケースを使用します。

于 2009-08-11T08:47:38.450 に答える
0
SELECT TOP(n) HasPicture --should be 0 or 1 to allow ORDER
   FROM Users
   ORDER BY 1
于 2009-08-11T08:06:46.083 に答える
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
      )
 )
于 2009-08-11T08:08:01.960 に答える