根据生成的随机数对结果集进行排名

时间:2019-05-01 11:39:04

标签: tsql

我有一个T-Sql查询,该查询为每个记录生成一个随机数。我还想做的是添加Rank或Row_Number列

我已经尝试了Rank和Row_Number,但是当我在order by子句中输入int时出现以下错误:

  

窗口函数,集合和NEXT VALUE FOR函数不   支持整数索引作为ORDER BY子句表达式

SELECT      TOP(4) PERCENT  CONVERT(VARCHAR(10),Getdate(),103) RunDate
        , EM.EmpCode 'Emp Code'
        , D.DepotDepotDescription 'Depot'
        , cast(rand(checksum(newid())) * 10 as decimal(8, 6)) [Random Number]
        , rank() OVER (order by 100) Row
FROM        ttimport.EmployeeMaster EM 
        LEFT OUTER JOIN ttimport.PayrollFrequency PF ON EM.FrequencyDesc = PF.DescCode
        LEFT OUTER JOIN ttimport.Departments DPT ON EM.DepartmentName = DPT.DescCode
        LEFT OUTER JOIN ttimport.Depot D ON EM.DepotDepotDescription = D.DescCode

ORDER BY 4

1 个答案:

答案 0 :(得分:1)

哦,我想我明白您的问题在这里。我假设您想基于rank的值来[Random Number]?如果是这样,请继续阅读!


您不能在order by中使用常量,并且不能期望它以任何方式排序,这就是为什么您的当前脚本引发错误的原因,因为rank需要排序顺序。

要引用您的Random Number列,您只需要将其包装在另一个select中,或使用cte到同一末端:

WITH data AS
(

    SELECT      TOP(4) PERCENT  CONVERT(VARCHAR(10),Getdate(),103) RunDate
            , EM.EmpCode 'Emp Code'
            , D.DepotDepotDescription 'Depot'
            , cast(rand(checksum(newid())) * 10 as decimal(8, 6)) [Random Number]
    FROM        ttimport.EmployeeMaster EM 
            LEFT OUTER JOIN ttimport.PayrollFrequency PF ON EM.FrequencyDesc = PF.DescCode
            LEFT OUTER JOIN ttimport.Departments DPT ON EM.DepartmentName = DPT.DescCode
            LEFT OUTER JOIN ttimport.Depot D ON EM.DepotDepotDescription = D.DescCode
)
SELECT *
      , RANK() OVER (ORDER BY [Random Number]) AS Ranking
FROM data
ORDER BY 4