简体   繁体   English

带顶部和分组依据的SQL Server查询

[英]SQL server query with top and group by

Given a table of the following structure: 给出具有以下结构的表:

subscriber_id,band subscriber_id,带

11,1 11,1

12,1 12,1

13,1 13,1

... ...

21,2 21,2

22,2 22,2

23,2 23,2

24,2 24,2

... ...

n1,n N1,N

n2,n N2,N

n3,n N3,N

... ...

nm,n 下,n

I want to get a subgroup of n% size of the subscribers from each group. 我想从每个组中得到一个n%的订户子组。 For 10%, I should get 10% of group 1, 10% of group 2... 10% of group n. 对于10%,我应该得到第1组的10%,第2组的10%...第n组的10%。

It sounds like you want a stratified sample. 听起来您想要分层样本。 You can get this by first enumerating within each group and then choosing the "n" records you want. 您可以通过首先在每个组中枚举,然后选择所需的“ n”条记录来获得此信息。 Here is an example of how to do this in SQL Server: 这是如何在SQL Server中执行此操作的示例:

select t.id, t.band
from (select t.*,
             row_number() over (order by band_seqnum) as seqnum
      from (select t.*,
                   row_number() over (partition by band order by rand(checksum()) as band_seqnum,
                   count(*) over () as cnt
            from t
           ) t
     ) t
where band_seqnum <= 0.10 * cnt;

Try This 尝试这个

Select * from 
(
Select *, NTILE(n%) over(partition by id order by id) 'R' from t)t
where t.R<=(n%)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM