我有一张这样的桌子。我想根据日期列对每一行进行排名,以便如果 record_number 和 date 的两个值相等,则最终结果是相同的排名;如果 record_number 和 date 不同,则最终结果是不同的排名。例如,下表中的前两行应为排名 1,而第三行应为排名 2,因为日期不同,但 record_number 相同。
记录编号 | 日期 |
---|---|
4648 | 2015-06-17 |
4648 | 2015-06-17 |
4648 | 2015-06-18 |
4897 | 2015-12-03 |
6523 | 2020-01-09 |
6523 | 2022-04-01 |
我使用了这个逻辑,但所有行都排名为 1。
ALTER TABLE main_clinics
ADD COLUMN visit_rank INTEGER;
UPDATE main_clinics
SET
visit_rank = (
SELECT DENSE_RANK() OVER (PARTITION BY record_number ORDER BY date ASC)
FROM main_clinics
);
您不需要
RANK
或 DENSE_RANK
:
UPDATE main_clinics AS mc
SET visit_rank = (
SELECT COUNT(*)
FROM (SELECT DISTINCT record_number, date FROM main_clinics) AS d
WHERE d.record_number = mc.record_number
AND d.date <= mc.date
);
如果您的 SQLite 版本是 3.33.0+,您可以使用返回所有排名的 cte,并使用
UPDATE...FROM
语法将其连接到表中:
WITH cte AS (
SELECT *, DENSE_RANK() OVER (PARTITION BY record_number ORDER BY date) AS rnk
FROM main_clinics
)
UPDATE main_clinics AS m
SET visit_rank = c.rnk
FROM cte AS c
WHERE c.record_number = m.record_number AND c.date = m.date;
查看演示。
对于旧版本的 SQLite,请使用相关子查询:
UPDATE main_clinics AS m1
SET visit_rank = (
SELECT COUNT(DISTINCT date)
FROM main_clinics AS m2
WHERE m2.record_number = m1.record_number AND m2.date <= m1.date
);
查看演示。