sql least函数在窗口函数中的具体应用

avatar
作者
筋斗云
阅读量:0

LEAST 函数是 SQL 中的一个聚合函数,它返回一组值中的最小值

以下是 LEAST 函数在窗口函数中的一个具体应用示例:

WITH sales_data AS (   SELECT     employee_id,     sale_date,     sale_amount   FROM     sales ), running_totals AS (   SELECT     employee_id,     sale_date,     sale_amount,     SUM(sale_amount) OVER (PARTITION BY employee_id ORDER BY sale_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total   FROM     sales_data ), min_max_running_totals AS (   SELECT     employee_id,     sale_date,     sale_amount,     running_total,     LEAST(       MIN(running_total) OVER (PARTITION BY employee_id ORDER BY sale_date ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING),       MAX(running_total) OVER (PARTITION BY employee_id ORDER BY sale_date ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)     ) AS min_max_running_total   FROM     running_totals ) SELECT   employee_id,   sale_date,   sale_amount,   running_total,   min_max_running_total FROM   min_max_running_totals; 

在这个示例中,我们首先计算每个员工的销售额累计总和(running_total)。然后,我们使用 LEAST 函数找到每个员工在当前销售日期之前的最小和最大累计总和(min_max_running_total)。这样,我们可以轻松地比较每个员工在不同销售日期的累计总和的最小值和最大值。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!