分析函数

在 SQL Server 中使用函数处理数据

Ana Voicu

Data Engineer

FIRST_VALUE()

FIRST_VALUE(numeric_expression) 
    OVER ([PARTITION BY column] ORDER BY column ROW_or_RANGE frame)
  • 返回有序集合中的第一个值。

OVER 子句组成

组件 状态 说明
PARTITION by column 可选 将结果集划分为分区
ORDER BY column 必需 对结果集排序
ROW_or_RANGE frame 可选 设置分区的边界范围
在 SQL Server 中使用函数处理数据

LAST_VALUE()

LAST_VALUE(numeric_expression) 
    OVER ([PARTITION BY column] ORDER BY column ROW_or_RANGE frame)
  • 返回有序集合中的最后一个值。
在 SQL Server 中使用函数处理数据

分区范围

RANGE BETWEEN start_boundary AND end_boundary
ROWS BETWEEN start_boundary AND end_boundary
边界 说明
UNBOUNDED PRECEDING 分区的第一行
UNBOUNDED FOLLOWING 分区的最后一行
CURRENT ROW 当前行
PRECEDING 前一行
FOLLOWING 下一行
在 SQL Server 中使用函数处理数据

FIRST_VALUE() 与 LAST_VALUE() 示例

SELECT
    first_name + ' ' + last_name AS name,
    gender,
    total_votes AS votes,    
    FIRST_VALUE(total_votes) 
    OVER (PARTITION BY gender ORDER BY total_votes) AS min_votes,
    LAST_VALUE(total_votes) 
        OVER (PARTITION BY gender ORDER BY total_votes 
                ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS max_votes
FROM voters;
| name            | gender | votes | min_votes | max_votes |
|-----------------|--------|-------|-----------|-----------|
| Michele Suarez  | F      | 20    | 20        | 189       |
| ...             | ...    | ...   | 20        | 189       |
| Marcus Jenkins  | M      | 16    | 16        | 182       |
| Micheal Vazquez | M      | 18    | 16        | 182       |
在 SQL Server 中使用函数处理数据

LAG() 与 LEAD()

LAG(numeric_expression) OVER ([PARTITION BY column] ORDER BY column)

  • 访问同一结果集中前一行的数据。

LEAD(numeric_expression) OVER ([PARTITION BY column] ORDER BY column)

  • 访问同一结果集中后一行的数据。
在 SQL Server 中使用函数处理数据

LAG() 与 LEAD() 示例

SELECT 
    broad_bean_origin AS bean_origin,
    rating,
    cocoa_percent,
    LAG(cocoa_percent) OVER(ORDER BY rating ) AS percent_lower_rating,
    LEAD(cocoa_percent) OVER(ORDER BY rating ) AS percent_higher_rating
FROM ratings
WHERE company = 'Felchlin'
ORDER BY rating ASC;
| bean_origin        | rating | cocoa_percent | percent_lower_rating | percent_higher_rating |
|--------------------|--------|---------------|----------------------|-----------------------|
| Grenada            | 3      | 0.58          | NULL                 | 0.62                  |
| Dominican Republic | 3.75   | 0.62          | 0.58                 | 0.64                  |
| Madagascar         | 3.75   | 0.64          | 0.74                 | 0.65                  |
| Venezuela          | 4      | 0.65          | 0.74                 | NULL                  |
在 SQL Server 中使用函数处理数据

Passons à la pratique !

在 SQL Server 中使用函数处理数据

Preparing Video For Download...