从两个连接列ORACLE获取max(DateTime)

时间:2013-03-19 08:20:07

标签: sql oracle max

我正在努力解决问题而且没有太多时间自己解决这个问题。

我的查询:

   Select distinct d.delivery_bay_code,dt.diary_type_desc, d.delivery_datetime, ddo.order_no , ddo.company_id_no,  ddo.no_of_cartons, s.supplier_name, c.company_name, sk.sku_desc, (pod.deliver_not_after_date)||' '||(pod.deliver_not_before_date)as delivery_window
     from diary d , dc_diary_order ddo , purch_order po ,purch_order_carton_sku pocs ,sku sk, purch_order_date pod,supplier s , diary_type dt , company c
    where ddo.diary_entry_id_no = d.diary_entry_id_no
      and po.order_no = ddo.order_no
      and po.company_id_no = ddo.company_id_no
      and s.supplier_id_no = po.supplier_id_no
      and s.company_id_no = po.company_id_no
      and dt.diary_type_code = d.diary_type_code
      and c.company_id_no = po.company_id_no
      and po.order_no = pocs.order_no
      and pocs.sku_id_no = sk.sku_id_no
      and po.company_id_no = 2
      and ddo.order_no = 1999
      order by delivery_datetime;

此查询返回仅有delivery_window不同的2条记录。例如13/APR/11 13/APR/11 and 12/APR/11 12/APR/11我希望它只返回最大日期时间(最新日期)。

例如:select max(delivery_datetime) from diary;

现在我尝试了上面这样的查询:

select... max(pod.deliver_not_after_date)||' '||(pod.deliver_not_before_date)as delivery_window ... from

但我收到错误ORA-00937: not a single-group group function

1 个答案:

答案 0 :(得分:1)

您错过GROUP BY上的pod.deliver_not_before_date,导致错误消息。

select... max(pod.deliver_not_after_date)||' '||(pod.deliver_not_before_date)as delivery_window ... from ..... GROUP BY pod.deliver_not_before_date

使用MAX()或任何其他分组函数时,所有其他没有分组函数的列必须放入SQL语句的GROUP BY部分。

要仅获取每个订单的最新日期行,您可以使用以下内容:

   select *
       from (
             Select distinct d.delivery_bay_code,dt.diary_type_desc, d.delivery_datetime, ddo.order_no , ddo.company_id_no,  ddo.no_of_cartons, s.supplier_name, c.company_name, sk.sku_desc, (pod.deliver_not_after_date)||' '||(pod.deliver_not_before_date)as delivery_window
             , max(pod.deliver_not_after_date) over (partition by ddo.order_no order by ddo.order_no) max_deliver_not_after_date
          from diary d , dc_diary_order ddo , purch_order po ,purch_order_carton_sku pocs ,sku sk, purch_order_date pod,supplier s , diary_type dt , company c
            where ddo.diary_entry_id_no = d.diary_entry_id_no
          and po.order_no = ddo.order_no
          and po.company_id_no = ddo.company_id_no
          and s.supplier_id_no = po.supplier_id_no
          and s.company_id_no = po.company_id_no
          and dt.diary_type_code = d.diary_type_code
          and c.company_id_no = po.company_id_no
          and po.order_no = pocs.order_no
          and pocs.sku_id_no = sk.sku_id_no
          and po.company_id_no = 2
          and ddo.order_no = 1999
          order by delivery_datetime)
      where deliver_not_after_date = max_deliver_not_after_date;