在另一个表中返回最近的日期

时间:2011-12-08 15:35:35

标签: sql oracle date

我有两个表,一个叫做Events,一个叫做Documents。每个表都有两个日期列,即开始和结束(因此,事件开始,事件结束,文档开始,文档结束)。两个表都由名为Customer_ID的字段链接。我有兴趣根据客户ID将最接近的相关事件开始(及其ID)日期返回到Doc开始日期,因此例如表中的数据可能如下所示:

Customer_ID DOC_ID      DOC_Start   DOC_END
A           12          22/01/2011  23/01/2011
A           13          01/12/2011  05/12/2011
C           22          13/03/2011  20/03/2011


Customer_ID Event_ID    Event_Start Event_END
A           J1          01/01/2011  23/01/2011
A           J2          04/12/2011  05/12/2011
C           J44         15/03/2011  20/03/2011

我希望最终结果显示出来:

Customer_ID DOC_ID  DOC_Start   DOC_END     Event_ID
A           12      22/01/2011  23/01/2011  J1
A           13      01/12/2011  05/12/2011  J2
C           22      13/03/2011  20/03/2011  J44

我尝试使用谷歌搜索解决方案,并尝试了一两个建议,但我找不到的任何示例似乎都是用于比较表中的日期,甚至是Oracle的日期。此外,我在SQL方面的知识相当有限,但我所接受的大多数都来自这里,所以非常感谢我已经收到的帮助。

编辑:另一个条件是我只想返回相关的事件/文档类型。所以我只想带回DOC_ID,其中DOC_TYPE是'Inquiry'或'Info',而Event_Type也是如此。

编辑:感谢文森特,我按照建议把它放在哪里(想想我到处都试过了,但那里!)我现在得到了所需的结果。

如果有兴趣的话,我会发布工作解决方案以供将来参考:

SELECT
*

FROM (SELECT 
O_ASSESSMENTS.ASM_SUBJECT_ID as "ID", 
O_ASSESSMENTS.ASM_ID as "Assessment ID", 
O_ASSESSMENTS.ASM_START_DATE as "Assessment Start",  
O_ASSESSMENTS.ASM_END_DATE as "Assessment End", 
O_SERVICE_EVENTS.SEV_ID as "Event ID", 
O_SERVICE_EVENTS.SEV_ACTUAL_DATE as "Event Start", 
O_SERVICE_EVENTS.SEV_OUTCOME_DATE as "Event End",
ROUND(O_ASSESSMENTS.ASM_START_DATE -O_SERVICE_EVENTS.SEV_ACTUAL_DATE,0) as "Likely",
  row_number() over(PARTITION BY  O_ASSESSMENTS.ASM_ID                                    
ORDER BY abs(O_ASSESSMENTS.ASM_START_DATE -  O_SERVICE_EVENTS.SEV_ACTUAL_DATE)) rn            
FROM 
O_ASSESSMENTS 
JOIN  O_SERVICE_EVENTS ON O_ASSESSMENTS.ASM_SUBJECT_ID = O_SERVICE_EVENTS.SEV_SUBJECT_ID
Where O_SERVICE_EVENTS.SEV_CODE IN ('t','t1') AND O_ASSESSMENTS.ASM_QSA_ID IN ('test','test1')  )  WHERE rn = 1 

2 个答案:

答案 0 :(得分:8)

您可以使用analytics

SELECT *
  FROM (SELECT d.customer_id, d.doc_id, d.doc_start, d.doc_end, e.event_id,
                row_number() over(PARTITION BY d.doc_id 
                                  ORDER BY abs(d.doc_start - e.event_start)) rn
           FROM doc d
           JOIN event e ON d.customer_id = e.customer_id
        /*WHERE CLAUSE*/)
 WHERE rn = 1

答案 1 :(得分:0)

加入EventsDocuments,仅选择最接近DOC_StartEvent_Start

的联接行
select D1.Customer_ID, D1.DOC_ID, D1.DOC_Start, D1.DOC_END, E1.Event_ID 
from Events E1, Documents D1
where E1.Customer_ID = D1.Customer_ID
and (D1.Customer_ID, D1.DOC_ID, E1.Event_ID) in
(
     select D2.Customer_ID, D2.DOC_ID, E2.Event_ID 
     from Events E2, Documents D2
     where E2.Customer_ID = D2.Customer_ID
     group by D2.Customer_ID, D2.DOC_ID, E2.Event_ID
     having abs(D2.DOC_Start - E2.Event_Start) = min(abs(D2.DOC_Start - E2.Event_Start))
);