将范围选择减少5个点直到特定行数

时间:2018-03-14 08:23:23

标签: sql sql-server tsql

我有一个包含两列compay id和revenueper的表。我想获取conpany列表,其中,如果此条件返回> = 60条记录,则yieldper> 50;然后罚款其他条件将条件减少5分,并在其中获取yieldper> 50-5并将点数减少5,直至计数为&gt ; = 60

请帮忙。

3 个答案:

答案 0 :(得分:0)

您似乎可以使用TOP ... WITH TIESORDER BY表达式将每个revenueper值向下舍入到最近的5:

SELECT TOP 60 WITH TIES
companyid,revenueper
FROM someTable
ORDER BY (revenueper/5) desc

(假设revenueper是某种整数类型)

答案 1 :(得分:0)

试试这段代码:

declare @threshold int = 50
declare @cnt int
declare @minNumberOfRows int = 60

select @cnt = COUNT(*) from MY_TABLE
where revenueper > @threshold

while @cnt < @minNumberOfRows
begin
    set @threshold -= 5
    select @cnt = COUNT(*) from MY_TABLE
    where revenueper > @threshold
end

select * from MY_TABLE
where revenueper > @threshold

答案 2 :(得分:0)

根据您的要求,这是最好的解决方案

  select a.* from Table a cross join(
  SELECT  revenue FROM Table order by revenue
  OFFSET 59 ROWS FETCH NEXT 1 ROWS ONLY) b where a.revenue>=b.revenue-b.revenue%5 

让我知道它是否有效