使用 SQL 中的 last_value 函数返回去年的值
我需要返回今年最后一个日期的最后一个值。问题是返回 SQL 中已经出现的最后一个值。
产品 | 日期 | 值 | Last_Value_Previous_Year |
---|---|---|---|
产品 A | 31/12/2020 | 5000.00 | 2000.00 |
产品 A | 01/01/2020 | 2000.00 | 2000.00 |
产品 A | 01/01/2021 | 1000.00 | 3000.00 |
产品 A | 01/02/2021 | 1500.00 | 3000.00 |
产品 A | 01/03/2021 | 1000.00 | 3000.00 |
产品 A | 01/04/2021 | 3000.00 | 3000.00 |
我需要:
产品 | 日期 | 值 | Last_Value_Previous_Year |
---|---|---|---|
产品 A | 31/12/2020 | 5000.00 | 5000.00 |
产品 A | 01/01/2020 | 2000.00 | 5000.00 |
产品 A | 01/01/2021 | 1000.00 | 3000.00 |
产品 A | 01/02/2021 | 1500.00 | 3000.00 |
产品 A | 01/03/2021 | 1000.00 | 3000.00 |
Prod A | 01/04/2021 | 3000.00 | 3000.00 |
对于 2020 年,它返回最后出现的日期的值,而它应该是该年的最后一个日期。我已经尝试使用查询
select
last_value(value) over (partition by Product order by to_char(date, 'YYYY'))
from table
I need to return the last value of the last date of the year. the problem is that the last value that already comes in SQL is being returned.
Product | Date | Value | Last_Value_Previous_Year |
---|---|---|---|
Prod A | 31/12/2020 | 5000.00 | 2000.00 |
Prod A | 01/01/2020 | 2000.00 | 2000.00 |
Prod A | 01/01/2021 | 1000.00 | 3000.00 |
Prod A | 01/02/2021 | 1500.00 | 3000.00 |
Prod A | 01/03/2021 | 1000.00 | 3000.00 |
Prod A | 01/04/2021 | 3000.00 | 3000.00 |
I need:
Product | Date | Value | Last_Value_Previous_Year |
---|---|---|---|
Prod A | 31/12/2020 | 5000.00 | 5000.00 |
Prod A | 01/01/2020 | 2000.00 | 5000.00 |
Prod A | 01/01/2021 | 1000.00 | 3000.00 |
Prod A | 01/02/2021 | 1500.00 | 3000.00 |
Prod A | 01/03/2021 | 1000.00 | 3000.00 |
Prod A | 01/04/2021 | 3000.00 | 3000.00 |
For the year 2020 it is returning the value of the last date that appears, when it should be the last of the year. I already tried to use the query
select
last_value(value) over (partition by Product order by to_char(date, 'YYYY'))
from table
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该查询将在 Oracle 中运行。
This query will work in Oracle.
我会在partition by语句中添加
to_char(date,'YYYY')
,以按产品+年份进行分组,并确保您拥有年份的最新值,然后按日期而不是年份排序(实际上,按年份排序并不会真正对数据进行排序)。因此,你可以尝试这个:
I would add
to_char(date,'YYYY')
in the partition by statement to group by product + year and ensure you'll have the latest value of the year, then order by date instead of year (actually, ordering by year will not really sort data).Thus, you could try this :