[英]Choose balanced records from a table due to a column value
I want to select records from a table which has a column with value -1 and +1 The ratio of -1 values to +1 values is about %17 我想从具有值-1和+1的列的表中选择记录。-1值与+1值的比率约为%17
But, I want to select records with balanced rate of -1 and +1 values. 但是,我想选择具有-1和+1值的平衡速率的记录。
For example I want to have select result with about %30 with -1 value and %70 with +1 value. 例如,我想要选择结果为%30的值为-1,而%70为+1的值。
For example I have the following data set: 例如,我有以下数据集:
A B -1
A C -1
C Y +1
C A +1
C B +1
B C -1
A D +1
A F +1
D F +1
C F +1
Then, for example with %50 balanced data, I want to choose 4 records from these with exactly 2 records with value -1 and 2 records with value +1. 然后,例如对于%50平衡数据,我想从中选择4条记录,其中2条记录的值为-1,2条记录的值为+1。
May you please help me how can I do this with SQL? 能否请您帮我如何使用SQL做到这一点?
Thank you 谢谢
since you didn't state the rules required clearly i could only guess this is what you want. 因为您没有明确说明所需的规则,所以我只能猜测这就是您想要的。
declare
@percentage_1 int,
@percentage_2 int,
@recs int,
@rn int,
@rp int
select
@percentage_1 = 50,
@percentage_2 = 50,
@recs = 4
select
@rn = @percentage_1 * @recs / 100,
@rp = @percentage_2 * @recs / 100
; with
cte as
(
select *, r = row_number() over (partition by value order by col1, col2)
from your_table
)
select *
from cte
where (value = -1 and r <= @rn)
or (value = +1 and r <= @rp)
order by value, col1, col2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.