小编典典

在其他表格中返回最近的日期

sql

我有两个表,一个称为“事件”,一个称为“文档”。每个表都有两个日期列,开始和结束(因此,事件开始,事件结束,文档开始,文档结束)。这两个表通过名为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_TYPE为“查询”或“信息”的DOC_ID,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

阅读 256

收藏
2021-04-28

共1个答案

小编典典

您可以使用分析

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
2021-04-28