last_value
是一個聚合函數,它用于獲取序列中的最后一個值
SELECT last_value(column_name) OVER (ORDER BY column_name ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_value
FROM table_name;
這里的 column_name
是你想要獲取最后值的列名,table_name
是你的表名。OVER
子句定義了窗口函數的范圍,ORDER BY
對數據進行排序,ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
表示窗口包含所有行。
例如,如果你有一個名為 sales
的表,其中包含一個名為 revenue
的列,你可以使用以下查詢來獲取最后一個值:
SELECT last_value(revenue) OVER (ORDER BY revenue ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_value
FROM sales;
請注意,這個查詢將返回表中每一行的最后值,而不僅僅是最后一行。如果你只想獲取最后一個值,可以使用以下查詢:
SELECT last_value(revenue) OVER (ORDER BY revenue ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_value
FROM sales
LIMIT 1;