使用windows函数确定滞后,前导和当前行的百分位差异?

时间:2017-10-14 11:12:46

标签: sql-server tsql

有没有更好的方法来使用Windows函数获取移动百分位而不使用CTE或派生表等?我希望在一个使用Windows函数的查询中使用它,但是我有一段时间将它转换为百分位值。我能想到的唯一解决方案是创建数值然后用表格进行数学运算。如果有更简化的方法可以做到这一点,那会很酷吗?

WITH numberdata AS
(
SELECT
    custid
    ,orderid
    ,LAG(VAL) OVER(PARTITION BY CUSTID ORDER BY ORDERID DESC) as lagval
    ,LEAD(VAL) OVER(PARTITION BY CUSTID ORDER BY ORDERID DESC) as leadval
    ,val - LAG(VAL) OVER(PARTITION BY CUSTID ORDER BY ORDERID DESC) as lagvaldiff
    ,val - LEAD(VAL) OVER(PARTITION BY CUSTID ORDER BY ORDERID DESC) as leadvaldiff
    ,val
FROM sales.ordervalues
)
select 
    CAST((lagval)/val AS NUMERIC(10,2)) as lagpctdiff
    ,CAST((leadval)/val AS NUMERIC(10,2)) as leadpctdiff
    ,CAST((lagvaldiff)/leadvaldiff AS NUMERIC(10,2)) as pctdiff
    ,val
    ,lagval
from numberdata
order by custid desc

这只是我学习如何在准备测试时更多地了解代码。数据来自位于训练db TSQL_2012中的sales.ordervalues表。

如何将leadvaldiff和lagvaldiff列转换为百分比而不将其放在CTE中?

dataset

1 个答案:

答案 0 :(得分:0)

我错过了什么,或者这就是你要找的东西?

// The Play plugin
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.6.5")

addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.7.0")