sum(lead_num) over(partition by course_model,dy_model,origin_channel,origin_fourth_level,origin_third_level,origin_second_level,origin_first_level,lead_date order by lead_date rows between 1 preceding and 1 following)
时间: 2024-03-16 19:45:31 浏览: 56
这是一个使用窗口函数进行累计求和的 SQL 语句。该语句使用了 `SUM` 函数和 `OVER` 子句来计算每一行的 `lead_num` 值与其前后相邻的两行的 `lead_num` 值之和。
具体来说:
- `PARTITION BY` 子句按照指定的列对数据进行分组,这里是 `course_model, dy_model, origin_channel, origin_fourth_level, origin_third_level, origin_second_level, origin_first_level, lead_date`,也就是在这些列相同的行被视为同一组。
- `ORDER BY` 子句按照 `lead_date` 列对每个分组内的行进行排序,这里是按照 `lead_date` 的先后顺序进行排序。
- `ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING` 子句指定了每一行的窗口范围,即将当前行和前一行、后一行的值相加。
因此,该语句会计算每个分组内每一行的 `lead_num` 与其前后相邻两行的 `lead_num` 之和。
例如,如果我们有以下数据:
```
course_model | dy_model | origin_channel | origin_fourth_level | origin_third_level | origin_second_level | origin_first_level | lead_date | lead_num
-------------|----------|------------------|-------------------------|------------------------|------------------------|----------------------|-----------|---------
course1 | dy1 | channel1 | fourth1 | third1 | second1 | first1 | 2021-01-01 | 10
course2 | dy2 | channel1 | fourth1 | third1 | second1 | first1 | 2021-01-01 | 5
course1 | dy1 | channel1 | fourth1 | third1 | second1 | first1 | 2021-01-02 | 8
course2 | dy2 | channel1 | fourth1 | third1 | second1 | first1 | 2021-01-02 | 6
```
则运行以下 SQL 语句:
```
SELECT
course_model,
dy_model,
origin_channel,
origin_fourth_level,
origin_third_level,
origin_second_level,
origin_first_level,
lead_date,
lead_num,
SUM(lead_num) OVER (
PARTITION BY course_model, dy_model, origin_channel, origin_fourth_level, origin_third_level, origin_second_level, origin_first_level, lead_date
ORDER BY lead_date
ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING
) AS lead_num_sum
FROM your_table;
```
将得到以下结果:
```
course_model | dy_model | origin_channel | origin_fourth_level | origin_third_level | origin_second_level | origin_first_level | lead_date | lead_num | lead_num_sum
-------------|----------|------------------|-------------------------|------------------------|------------------------|----------------------|-----------|-----------|-------------
course1 | dy1 | channel1 | fourth1 | third1 | second1 | first1 | 2021-01-01 | 10 | 18
course2 | dy2 | channel1 | fourth1 | third1 | second1 | first1 | 2021-01-01 | 5 | 11
course1 | dy1 | channel1 | fourth1 | third1 | second1 | first1 | 2021-01-02 | 8 | 18
course2 | dy2 | channel1 | fourth1 | third1 | second1 | first1 | 2021-01-02 | 6 | 11
```
其中,`lead_num_sum` 列即为每个分组内每一行的 `lead_num` 与其前后相邻两行的 `lead_num` 之和。
阅读全文