在特定列SQL Server上随机选择记录的百分比

时间:2017-05-03 10:58:10

标签: sql sql-server database

我从表中选择随机的不同数据,它工作正常。该数据还有一个城市列。我想根据特定城市的百分比选择随机记录。就像我想要从表中排名前100的随机记录,但它应该是纽约的20%,德克萨斯的50%和拉斯维加斯的30%。如何在此查询中执行此操作需要建议

select distinct top 10 
    c.Phone, NEWID() as ArrangeOrder,
    max(c.city) as 'City', max(c.id),
    max(c.province) as 'Province', max(c.MediaSourceType), 
    max(c.[PrimarySelfie])  
from 
    Contestants c (nolock) 
inner join
    SocialMediaHashTags st  (nolock) on c.id = st.contestantid where st.contenttype = 1 
                                     and c.IsWinner = 0 
                                     and st.PostDate >= '04-25-2017 00:00:00' 
                                     and st.PostDate <= '04-25-2017 23:59:59' 
                                     and c.city is not null 
                                     and c.Province is not null 
                                     and c.CityId is not null 
                                     and c.CityId > 0
group by 
    c.Phone
order by 
    NEWID()

2 个答案:

答案 0 :(得分:0)

如果没有更多细节,很难理解你正在做什么,

但是,如果您只是想要请求配额,您可以提出3个不同的请求,每个配额一个,并限制答案数。

请详细说明您正在做的事情,例如您是否正在使用php或仅使用sql请求等...

答案 1 :(得分:0)

我不确定查询究竟是如何与问题相关的。如果您有包含城市列的数据 - 以及“Vegas”和“Texas”等值,您可以这样做:

select t.*
from (select t.*,
             row_number() over (partition by city order by newid()) as seqnum
      from t
     ) t
where (t.city = 'NewYork' and seqnum <= 20) or
      (t.city = 'Texas' and seqnum <= 50) or
      (t.city = 'Vegas' and seqnum <= 30);