[英]SQL server query with top and group by
給出具有以下結構的表:
subscriber_id,帶
11,1
12,1
13,1
...
21,2
22,2
23,2
24,2
...
N1,N
N2,N
N3,N
...
下,n
我想從每個組中得到一個n%的訂戶子組。 對於10%,我應該得到第1組的10%,第2組的10%...第n組的10%。
聽起來您想要分層樣本。 您可以通過首先在每個組中枚舉,然后選擇所需的“ n”條記錄來獲得此信息。 這是如何在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;
嘗試這個
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.