This is one way of solving it...
TEST_TBL is the one from which the customer records are selected, and MASTER_TBL contains the final results with indicators!
CREATE TABLE MASTER_TBL(
ID INTEGER,
INSERT_DT DATE,
VALID_IND INTEGER
) PRIMARY INDEX (ID)
CREATE TABLE TEMP_TBL(
ID INTEGER,
INSERT_DT DATE
) PRIMARY INDEX (ID)
INSERT INTO MASTER_TBL SELECT 1, CURRENT_DATE - INTERVAL '7' MONTH, 1;
INSERT INTO MASTER_TBL SELECT 1, CURRENT_DATE - INTERVAL '6' MONTH, 0;
INSERT INTO MASTER_TBL SELECT 2, CURRENT_DATE - INTERVAL '5' MONTH, 1;
INSERT INTO MASTER_TBL SELECT 3, CURRENT_DATE - INTERVAL '6' MONTH, 1;
INSERT INTO TEMP_TBL SELECT '1', CURRENT_DATE - INTERVAL '7' MONTH;
INSERT INTO TEMP_TBL SELECT '3', CURRENT_DATE - INTERVAL '6' MONTH;
INSERT INTO TEMP_TBL SELECT '2', CURRENT_DATE - INTERVAL '5' MONTH;
INSERT INTO MASTER_TBL
SEL A.ID, A.INSERT_DT, CASE WHEN A.INSERT_DT - INTERVAL '6' MONTH > B.INSERT_DT THEN 1 ELSE 0 END
FROM TEMP_TBL A
INNER JOIN
(
SEL ID, INSERT_DT, VALID_IND
FROM MASTER_TBL
WHERE VALID_IND = 1
QUALIFY ROW_NUMBER() OVER(PARTITION BY ID ORDER BY INSERT_DT DESC) = 1
) B
ON A.ID = B.ID
↧