第一个查询也适用于 mysql 5.x。
第二种使用仅在 mysql 8 中支持的窗口函数
CREATE TABLE datetable (
`Id` INTEGER,
`unique_identifier` INTEGER,
`reference_date` Date
);
INSERT INTO datetable
(`Id`, `unique_identifier`, `reference_date`)
VALUES
('1', '123456789', '2020-01-05'),
('2', '123456789', '2020-02-20'),
('3', '123456789', '2020-06-29'),
('4', '987654321', '2020-02-21'),
('5', '987654321', '2020-03-30');
SELECT
`Id`, `reference_date`
,IF(@unique_identifier = `unique_identifier`,IF(DATEDIFF(`reference_date`,@date) > 60,1,0),1) 60_days_since_seen
,@unique_identifier := `unique_identifier` as 'unique_identifier'
,@date :=`reference_date` 'reference_date'
FROM
(SELECT * FROM datetable ORDER BY unique_identifier,reference_date) t1
,(SELECT @unique_identifier := 0) a,(SELECT @date := NOW()) b
身份证 | 参考日期 | 60_days_since_seen | 唯一标识符 | 参考日期
-: | :------------- | -----------------: | ----------------: | :-------------
1 | 2020-01-05 | 1 | 123456789 | 2020-01-05
2 | 2020-02-20 | 0 | 123456789 | 2020-02-20
3 | 2020-06-29 | 1 | 123456789 | 2020-06-29
4 | 2020-02-21 | 1 | 987654321 | 2020-02-21
5 | 2020-03-30 | 0 | 987654321 | 2020-03-30
SELECT
`Id`, `unique_identifier`, `reference_date`,
IF(DATEDIFF(reference_date , LAG(reference_date) OVER (
PARTITION BY unique_identifier
ORDER BY reference_date ))> 60 OR LAG(reference_date) OVER (
PARTITION BY unique_identifier
ORDER BY reference_date ) is NULL,1,0) 60_days_since_seen
FROM datetable
身份证 | 唯一标识符 | 参考日期 | 60_days_since_seen
-: | ----------------: | :------------- | -----------------:
1 | 123456789 | 2020-01-05 | 1
2 | 123456789 | 2020-02-20 | 0
3 | 123456789 | 2020-06-29 | 1
4 | 987654321 | 2020-02-21 | 1
5 | 987654321 | 2020-03-30 | 0
db<>在这里摆弄