SQL first_value() 按特定日期部分
SQL first_value() by specific datepart
我有数据,其中包含特定日期 (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;
我有数据,其中包含特定日期 (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;