2013-03-19 77 views
0

我正在爲某件事而掙扎,而且沒有太多時間來自己弄清楚。從兩個級聯列表中獲取最大值(DateTime)ORACLE

我的查詢:

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; 

這個查詢帶回2條記錄,其中只有delivery_window不同。例如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

+0

:那是SQL的基礎上,如果你想最大記錄中,你需要把非在你的查詢中,你使用了不同的子句,它可以給你多個記錄,那麼如果你希望你可以使用分析函數,那麼獲得最大交付日期的標準是什麼? – 2013-03-19 08:29:31

+1

僅供參考:最大值將應用僅限於max(date1)。您不會從日期範圍中獲取最大值(日期1)||' 「|| DATE2。 – Art 2013-03-19 15:09:48

回答

1

你缺少GROUP BYpod.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;