SQL first_value()按特定日期划分

时间:2019-02-24 15:38:18

标签: sql tsql window-functions 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()中。我们该怎么做?

1 个答案:

答案 0 :(得分:1)

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