SQL Server:计算列值与其他列值相比有多大
我的表列填充了浮点值,例如:
id-Values
1- 0.19230769230769232
2- 8.4848484848484854E
3- 0.10823529411764705
4- 0.05459770114942529
...
我想知道:是否有一个 SQL 函数允许我返回所选行位置与其他行位置相比的百分比?
例如: 我想知道是否有一种简单的方法来检查第 4 行是否在 TOP 10%
中。或者,如果第 2 行位于 LAST 10%
中(按值排序)。
我知道不可能使用 SQL Server 执行 SELECT TOP 10%
或 SELECT LAST 10%
,但这只是为了给出我想要做的事情的示例。
@解决方案:
declare @a int
declare @b int
declare @values float
select @values = values from test where id <= 2
select @a = count(*) from test where values <= @values
select @b = count(*) from test
select cast( cast(@a as float) / cast(@b as float) as float) * 100 as percentage
I have table column filled with float values e.g.:
id-Values
1- 0.19230769230769232
2- 8.4848484848484854E
3- 0.10823529411764705
4- 0.05459770114942529
...
I would like to know: is there a SQL function that allows me to return a percentage of the selected row position compared to the others?
For example:
I want to know if there is an easy way to check if the row 4 is in the TOP 10%
. Or if the row 2 is in the LAST 10%
(order by values).
I know it's not possible to do a SELECT TOP 10%
or a SELECT LAST 10%
with SQL Server but it's just to give an example of what I want to do.
@Solution:
declare @a int
declare @b int
declare @values float
select @values = values from test where id <= 2
select @a = count(*) from test where values <= @values
select @b = count(*) from test
select cast( cast(@a as float) / cast(@b as float) as float) * 100 as percentage
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一种方法。根据示例数据集,
这将根据 @Id 中设置的所需 Id 值返回类似您正在查找的百分比之类的内容:
我不太喜欢这样,因为它需要两次表扫描。可以根据应用程序还需要做什么来设计快捷方式。
Here's one way to do it. Based on the sample data set
this will return the something like the percentage that you're looking for, based on the desired Id value as set in @Id:
I don't much like this, as it requires two table scans. Shortcuts might be devised, depending on what else the application needs to do.
检查以下代码是否对您有帮助。
Check if following code help you.
好的,这应该是 SQL 2000 兼容版本。基于与我之前的答案相同的表结构:
假设 Id 上有索引,现在只有 1 次表扫描。如果出现重复值,这将根据第一次出现的情况选择位置。搞乱+1;如果没有它,第一个值将为您提供 0%,如果有它,如果有四行,您将获得 25%——那么什么才是适合您的应用程序的呢?另外,如果表为空,您将收到除以零的错误,因此您需要根据您的应用程序来处理该错误。
Ok, this should be a SQL 2000 compatible version. Based on the same table structure as my prior answer:
Assuming an index on Id, there's now only 1 table scan. In case of duplicate values, this will select the position based on the first occurance. Mess around with that +1; without it, the first value will get you 0%, with it, with four rows you'd get 25% -- so what is right for your application? Also, if the table is empty, you'll get a divide by zero error, so you'll need to handle that as appropriate to your application.