我有两张表,一张叫 Events,一张叫 Documents。每个表都有两个日期列,开始和结束(因此事件开始、事件结束、文档开始、文档结束)。两个表都由一个名为 Customer_ID 的字段链接。我有兴趣根据客户 ID 将最接近的相关事件开始(及其 ID)日期返回到文档开始日期,例如表中的数据可能如下所示:
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 也是如此。
编辑:谢谢文森特,我按照建议将 where 放入(我想我已经在任何地方都试过了!),现在我得到了所需的结果。
如果有人感兴趣,我会发布工作解决方案以供将来参考:
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
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