我有以下代码,我从表中选择LossAmount值,我在其中创建一个序列列和LossAmount列,并根据特定的序列号选择LossAmount值。
declare @percent float
set @percent = 0.95
select LossAmount
from (select LossAmount, seq = ROW_NUMBER() over (order by LossAmount desc) from dbo.TestXB_TotalLoss) as p
where p.seq =((select COUNT(*) from dbo.TestXB_TotalLoss)-((select COUNT(*) from dbo.TestXB_TotalLoss)*@percent))
所以说我的LossAmount列有1000行,p.seq等式是1000-1000(0.95)
。我在该序列号(即50)处选择LossAmount值。
就我而言,我的参数是一个标量。 如果我想要计算各种百分比,如何更新我的代码?我有下表,dbo.Percentiles
Percentiles
0.4
0.6
0.996
对于我的输出,我想要这样的东西。
Percentiles LossAmount
0.4 ...some #...
0.6 ...some #...
0.996 ...some #...
任何帮助将不胜感激。
答案 0 :(得分:0)
这总比我想象的要难。挑战是排除一排。我认为以下是:
select pt.pcent, min(LossAmount)
from (select tl.*, p.pcent, ROW_NUMBER() over (order by LossAmount desc) as seqnum,
count(*) over () as totnum
from dbo.TestXB_TotalLoss cross join
(select 0.95 as pcent
) p
) pt
where totnum*pcent - seqnum >= 0 and totnum*pcent - seqnum < 1
这会将百分比移动到内部表p
并进行交叉连接。然后,它会选择计划行号(totnum*pcent
)与实际行号(seqnum
)之间的差异为非负且小于1的行。
我没有测试过这个特定的查询,因此可能会出现语法错误。
答案 1 :(得分:0)
我认为这应该是你,有更清晰的方法来编写它,但我想尽可能少地改变你的代码......
select LossAmount, n.percentiles
from (select LossAmount,
seq = ROW_NUMBER() over (order by LossAmount desc)
from dbo.TestXB_TotalLoss) as p
join (Select ((select COUNT(*) from dbo.TestXB_TotalLoss)-((select COUNT(*) from dbo.TestXB_TotalLoss)*percentiles)) As seq, percentiles
From dbo.Percentiles) n
On p.seq = n.seq