首页 > 解决方案 > 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() 中。我们怎么能做到这一点?

标签: sqltsqlwindow-functionsdatepart

解决方案


您可以将年份放入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;

推荐阅读