【问题标题】:Oracle SQL Query -- records since 2017Oracle SQL 查询——自 2017 年以来的记录
【发布时间】:2020-11-17 17:09:36
【问题描述】:

我有一个怪物查询,我需要返回自 2017 年 1 月 1 日以来创建的所有记录,但 DataGrip 正在返回

[42000][904] ORA-00904:“YEAR”:无效标识符位置:1283

SELECT
       inh.inh_auto_key, inh.invc_number,
       inh.invoice_date, inh.ship_date, inh.post_status, inh.post_date,
       pnm.pn, pnm.description,
       stm.serial_number, stm.unit_freight_cost,
       sod.unit_price, sod.unit_cost, sod.qty_invoiced, sod.sod_auto_key,
       condition_code,
       salesperson_code,
       so_number,
       ind.route_code, ind.ind_auto_key,
       company_name, company_code,
       consignment_code,
       term_code, due_days
FROM
  invc_header inh
    JOIN invc_detail ind ON ind.inh_auto_key = inh.inh_auto_key
    JOIN so_detail sod ON sod.sod_auto_key = ind.sod_auto_key
    JOIN so_header soh ON soh.soh_auto_key = sod.soh_auto_key
    JOIN part_condition_codes pcc ON pcc.pcc_auto_key = sod.pcc_auto_key
    LEFT JOIN salesperson spn on spn.spn_auto_key = soh.spn_auto_key
    JOIN companies cmp ON cmp.cmp_auto_key = soh.cmp_auto_key
    LEFT JOIN stock_reservations str ON str.sod_auto_key = sod.sod_auto_key
    LEFT JOIN stock stm ON stm.stm_auto_key = str.stm_auto_key
    LEFT JOIN parts_master pnm on pnm.pnm_auto_key = stm.pnm_auto_key
    LEFT JOIN consignment_codes cnc on cnc.cnc_auto_key = stm.cnc_auto_key
    LEFT JOIN term_codes tmc on tmc.tmc_auto_key = cmp.tmc_auto_key
WHERE ind.route_code IN ('M', 'E', 'S')
  AND Year(inh.invoice_date) > 2017

【问题讨论】:

  • 这看起来像一个标准的 Oracle 函数docs.oracle.com/javadb/10.8.3.0/ref/rrefyearfunc.html
  • 顺便说一句,你应该使用>=。否则以1/1/2018开头。
  • 您使用的是哪个 Oracle 版本?
  • 我真的不知道是哪个版本
  • 最近的版本中不存在YEAR函数,你必须使用EXTRACT

标签: sql oracle datetime where-clause date-arithmetic


【解决方案1】:

它仍在打磨,但我认为这会奏效

WHERE ind.route_code IN ('M', 'E', 'S')
  AND EXTRACT(YEAR from inh.invoice_date) > 2017

【讨论】:

    【解决方案2】:

    我会推荐:

    inh.invoice_date > date '2017-01-01'
    

    虽然您发布的使用extract() 的代码在Oracle 中有效,但上述解决方案更有效。由于没有对要过滤的列应用任何函数,因此可以利用日期列上的索引。另一方面,您的解决方案需要在过滤发生之前将该函数应用于整个列。随着要过滤的行数变大,性能损失会迅速增加。

    用技术术语来说,上面的表达式是SARGable,代表Search Argument Able。

    【讨论】:

      猜你喜欢
      • 2019-08-01
      • 2021-05-28
      • 2014-10-18
      • 1970-01-01
      • 1970-01-01
      • 2019-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多