我有两个表CALL_DATA
和MASTER_DATA
。
主数据具有客户的日常数据,CALL_DATA
具有一些客户的呼叫以及其他一些数据。
我想为MASTER_DATA
中每位客户及其每天的每一行获取最近的日期(直到现在的最大日期)为CALL_DATA
的行。
我想出了这个
SELECT MAX(CALL_DATA.CALL_DATE) OVER (PARTITION BY MASTER_DATA.CUSTOMER_ID
ORDER BY MASTER_DATA.DAILY_START_DATE)
AS max_date_agg
, MASTER_DATA.*
, CALL_DATA.*
FROM MASTER_DATA, CALL_DATA
WHERE CALL_DATA.CALL_DAT <= MASTER_DATA.DAILY_START_DATE
AND CALL_DATA.CUSTOMER_ID = MASTER_DATA.CUSTOMER_ID;
但是,对于每个每日开始日期,这都会给我带来不止一次的直播。
实际上,它返回的行数与CALL_DATA
表中的行一样多,直到DAILY_START_DATE
中的MASTER_DATA
。
示例:
MAX_DATE_AGG CUSTOMER_ID DAILY_START_DATE
24/10/17 00:00:00,000000000 100664970 24/10/17 00:00:00
24/10/17 00:00:00,000000000 100664970 25/10/17 00:00:00
24/10/17 00:00:00,000000000 100664970 26/10/17 00:00:00
24/10/17 00:00:00,000000000 100664970 27/10/17 00:00:00
24/10/17 00:00:00,000000000 100664970 28/10/17 00:00:00
24/10/17 00:00:00,000000000 100664970 29/10/17 00:00:00
24/10/17 00:00:00,000000000 100664970 30/10/17 00:00:00
24/10/17 00:00:00,000000000 100664970 31/10/17 00:00:00
24/10/17 00:00:00,000000000 100664970 01/11/17 00:00:00
24/10/17 00:00:00,000000000 100664970 02/11/17 00:00:00
24/10/17 00:00:00,000000000 100664970 03/11/17 00:00:00
24/10/17 00:00:00,000000000 100664970 04/11/17 00:00:00
24/10/17 00:00:00,000000000 100664970 05/11/17 00:00:00
24/10/17 00:00:00,000000000 100664970 06/11/17 00:00:00
24/10/17 00:00:00,000000000 100664970 07/11/17 00:00:00
24/10/17 00:00:00,000000000 100664970 08/11/17 00:00:00
24/10/17 00:00:00,000000000 100664970 09/11/17 00:00:00
24/10/17 00:00:00,000000000 100664970 10/11/17 00:00:00
24/10/17 00:00:00,000000000 100664970 11/11/17 00:00:00
24/10/17 00:00:00,000000000 100664970 12/11/17 00:00:00
24/10/17 00:00:00,000000000 100664970 13/11/17 00:00:00
24/10/17 00:00:00,000000000 100664970 14/11/17 00:00:00
15/11/17 00:00:00,000000000 100664970 15/11/17 00:00:00
15/11/17 00:00:00,000000000 100664970 15/11/17 00:00:00
15/11/17 00:00:00,000000000 100664970 16/11/17 00:00:00
15/11/17 00:00:00,000000000 100664970 16/11/17 00:00:00
15/11/17 00:00:00,000000000 100664970 17/11/17 00:00:00
15/11/17 00:00:00,000000000 100664970 17/11/17 00:00:00
15/11/17 00:00:00,000000000 100664970 18/11/17 00:00:00
15/11/17 00:00:00,000000000 100664970 18/11/17 00:00:00
答案 0 :(得分:4)
您可以将查询转换为相关子查询:
SELECT MASTER_DATA.*, (
SELECT MAX(CALL_DATE)
FROM CALL_DATA
WHERE CALL_DATA.CUSTOMER_ID = MASTER_DATA.CUSTOMER_ID
AND CALL_DATA.CALL_DAT <= MASTER_DATA.DAILY_START_DATE
) AS MOST_RECENT_CALL_TILL_NOW
FROM MASTER_DATA
答案 1 :(得分:2)
此查询应返回您想要的内容
SELECT T.*
FROM (
SELECT RANK() OVER (PARTITION BY MASTER_DATA.CUSTOMER_ID, MASTER_DATA.DAILY_START_DATE ORDER BY CALL_DATA.CALL_DATE DESC) AS myrank,
MASTER_DATA.CUSTOMER_ID,
MASTER_DATA.DAILY_START_DATE,
CALL_DATA.CALL_DATE
FROM MASTER_DATA,
CALL_DATA
WHERE CALL_DATA.CALL_DATE <= MASTER_DATA.DAILY_START_DATE
AND CALL_DATA.CUSTOMER_ID = MASTER_DATA.CUSTOMER_ID
) T
WHERE myrank = 1
;