简体   繁体   English

Oracle SQL:每年查询 YTD

[英]Oracle SQL: Query YTD for every year

How would I write an Oracle SQL query to pull every record from a table where the date is less than or equal to this day of that year?我将如何编写 Oracle SQL 查询以从日期小于或等于当年这一天的表中提取每条记录?

For example:例如:

My table:我的表:

date_field日期字段
01/01/2010 01/01/2010
12/31/2010 12/31/2010
01/01/2021 01/01/2021
07/21/2021 07/21/2021

My goal if the query was ran on 07/21/2021如果查询是在 2021 年 7 月 21 日运行的,我的目标

date_field日期字段
01/01/2010 01/01/2010
01/01/2021 01/01/2021
07/21/2021 07/21/2021

You can convert the month/day to a string and compare:您可以将月/日转换为字符串并进行比较:

select t.*
from t
where to_char(date_field, 'MMDD') < to_char(sysdate, 'MMDD');

This is a potential solution.这是一个潜在的解决方案。

  SELECT date_field
        FROM sample_data
       WHERE date_field <=
             TO_DATE (
                  (   TO_CHAR (SYSDATE, 'MM/DD/')
                   || EXTRACT (YEAR FROM date_field))
                     ,'MM/DD/RRRR')

Another option is to extract and compare the months and days as numbers:另一种选择是提取月份和日期并将其作为数字进行比较:

select date_field
from your_table
-- any earlier month
where extract(month from date_field) < extract(month from sysdate)
or (
  -- any earlier or same day in this month
  extract(month from date_field) = extract(month from sysdate)
  and extract(day from date_field) <= extract(day from sysdate)
)
order by date_field

db<>fiddle 数据库<>小提琴

With this or @Gordon's string approach, you might benefit from function-based indexes, though unless your data is really skewed towards the end of the year they probably wouldn't help here.使用这种方法或@Gordon 的字符串方法,您可能会从基于函数的索引中受益,但除非您的数据在年底时确实存在偏差,否则它们可能不会有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM