ral*_*alu 5 postgresql window-functions
我刚刚进入了窗口函数的世界。我有一个类似的问题要解决这个问题。
我有这张桌子:
最后一列(%Grown)
由下式给出:
-(1 - price of row 2 / price of row 1) * 100
Run Code Online (Sandbox Code Playgroud)
到目前为止,我发现的所有信息都与所有行的总和、平均值有关。我不知道如何绑定两行,所以我可以计算百分比。
我如何将其翻译成 SQL?
我认为最好的方法是使用LAG()
orLEAD()
函数:
SELECT *,
- 100.0 * (1 - LEAD(Price) OVER (ORDER BY t.Id) / Price) AS Grown
FROM table_name AS t
ORDER BY t.Id ;
Run Code Online (Sandbox Code Playgroud)
随着LEAD(Price) OVER (ORDER BY t.Id)
您可以访问到下一个Price
当行被订购Id
。目前尚不清楚顺序应该是什么。根据问题中的数据,您可能需要(ORDER BY Price DESC)
.
mou*_*iin -1
您可以使用公共表表达式,
WITH Data as (select ROW_NUMBER() OVER (ORDER BY applicable_date) as RowId, date, qty, price, [value] from tbl
)
SELECT
CurrentRow.date, CurrentRow.qty, CurrentRow.price, CurrentRow.[value], 'Your calculation here for Growth'
FROM Data as CurrentRow
LEFT OUTER JOIN Data as NextRow ON NextRow.RowId = CurrentRow.RowId + 1
WHERE NextSlice.RowId IS NOT NULL
Run Code Online (Sandbox Code Playgroud)
我希望它有帮助。
归档时间: |
|
查看次数: |
11428 次 |
最近记录: |