简体   繁体   English

选择具有较高价值而很少具有较低价值的行

[英]Select row with mostly higher value and rarely lower value

I'm trying to select a random row from a table, but there is a column in this table called Rate , I want it to return the row that has a higher rate, and rarely ever return the rows that has a lower rate, is this possible? 我正在尝试从表中选择随机行,但是此表中有一列称为Rate ,我希望它返回具有较高利率的行,而很少返回具有较低利率的行,这可能吗?

Table : 表:

CREATE TABLE _Random (Code varchar(128), Rate tinyint)

So you want a random row, but weighted towards the ones with higher rates? 因此,您想要一个随机的行,但权重较高的行呢?

It would also be good to know how many rows there are in the table - sorting the whole lot is kinda expensive. 知道表中有多少行也很好-对整个批次进行排序非常昂贵。 You may prefer to use a row_number concept than sorting by N guids. 您可能更喜欢使用row_number概念,而不是按N个向导排序。

So... One option could be to generate a single number, and then divide 100 by it. 所以...一种选择是生成一个数字,然后除以100。 Imagine we generate a number between 0 and 1. 假设我们生成一个介于0和1之间的数字。

.25 gives us 400, .5 gives us 200, .75 gives us 133... Notice that there's a curve here - so the numbers closer to 100 come up more often (subtract 100 to make the range start at 1). .25给我们400,.5给我们200,.75给我们133 ...请注意,这里有一条曲线-因此更接近100的数字出现的频率更高(减去100可使范围从1开始)。

You could use RAND() for a single value between 0 and 1 (it's probably good enough), and then do the division and subtraction to get a number. 您可以将RAND()用于0到1之间的单个值(可能足够好),然后进行除法和减法以获得一个数字。 If this is higher than the count of records, then maybe repeat? 如果这高于记录数,那么是否可以重复? But try to choose a value for your division that suits. 但是,请为您的部门选择合适的值。

If you need to weight it more, you could raise your RAND() value by some number, to flatten it out or steepen it up. 如果需要增加权重,则可以将RAND()值提高一些,以使其变平或变陡。 Do some experimenting to see how it looks. 做一些实验看看它的外观。

This query will fetch a random record which has an above average rate 此查询将获取随机记录,该记录的平均速率高于平均水平

SELECT TOP (1) * FROM _Random 
WHERE Rate>(SELECT AVG(Rate) FROM _Random)
ORDER BY NEWID()

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

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