sql - SQL first_value() 按特定日期部分
问题描述
我有数据,其中包含特定日期(yyyy-mm-dd)及其城市和价值
-------------------------------------
city | date | value
-------------------------------------
city A | 2018-05-01 | 10
city A | 2018-04-03 | 15
city A | 2019-01-03 | 9
city A | 2019-05-01 | 13
city B | 2019-05-01 | 12
city B | 2019-02-12 | 11
我想在下一列中获得按城市划分的每年的第一个值:
--------------------------------------------------
city | date | value | first_value_year_by_city
--------------------------------------------------
city A | 2018-05-01 | 10 | 15
city A | 2018-04-03 | 15 | 15
city A | 2019-01-03 | 9 | 9
city A | 2019-05-01 | 13 | 9
city B | 2019-05-01 | 12 | 11
city B | 2019-02-12 | 11 | 11
为此,我使用了 SQL:
select *,
,first_value(value) over(partition by city order by date rows between unbounded preceding and unbounded following) as first_value_year_by_city
from table
但我不能将 datepart(year,date) = 2018 和 datepart(year,date) = 2019 放在 first_value() 中。我们怎么能做到这一点?
解决方案
您可以将年份放入partition by
:
select t.*,
first_value(value) over (partition by city, year(date)
order by date
) as first_value_year_by_city
from table t;
推荐阅读
- javascript - 嵌套查询在 Node.js 和 MySQL 中不起作用
- c# - 如何在 C# 中向数据库中插入数据
- android - 在传递单击的自定义列表项的数据时单击带有 RecyclerView 的片段的项目时如何打开新活动?
- php - 防止列低于零和回显警告
- c - helloworld 内核模块中的 insmod 错误:模块格式无效
- python-3.x - 分组依据和 values_counts
- r - 使用 devtools 开发 htmlwidgets
- reactjs - 如何在页面加载时为反应应用程序实现动画
- reactjs - 尽管使用 async 和 await ,但数据未定义
- shell - 如何修复 Ubuntu 18.04 中的以下错误?