Select 最近 7 天按日期记录并避免按特定列重复

Select last 7 days records by date and avoid duplicates by specific column

我很确定我面临的问题很小,但我不知道出了什么问题。

我的 sql 中有以下 table:

+-----+------------------+---------------------+
| ID  | EMAIL            | VISIT               |
+-----+------------------+---------------------+
| 1   | john@email.com   | 2021-04-01,13:20:23 |
| 2   | peter@email.com  | 2021-04-03,12:03:44 |
| 3   | daniel@email.com | 2021-04-04,13:21:12 |
| 4   | john@email.com   | 2021-04-06,09:34:31 |
| 5   | peter@email.com  | 2021-04-07,11:20:22 |
+-----+------------------+---------------------+

我想显示最近 7 天的记录,但按最新日期排序并且每封电子邮件仅显示最新记录,如下所示

+-----+------------------+---------------------+
| ID  | EMAIL            | VISIT               |
+-----+------------------+---------------------+
| 3   | daniel@email.com | 2021-04-04,13:21:12 |
| 4   | john@email.com   | 2021-04-06,09:34:31 |
| 5   | peter@email.com  | 2021-04-07,11:20:22 |
+-----+------------------+---------------------+

我试过这个查询来实现这个:

尝试 1:SELECT * FROM table WHERE VISIT BETWEEN (NOW() - INTERVAL 7 DAY) AND NOW() GROUP BY EMAIL ORDER BY VISIT DESC

尝试 2:SELECT DISTINCT (EMAIL) FROM table WHERE VISIT BETWEEN (NOW() - INTERVAL 7 DAY) AND NOW() ORDER BY VISIT DESC

结果显示正确,但顺序奇怪。 如果我放弃 GROUP BY 子句,它会正确显示,但也会包含重复的 EMAIL 列。

尝试将 MAX 与分组依据一起使用

SELECT EMAIL,MAX(VISIT)  as last_visit FROM table WHERE VISIT BETWEEN (NOW() - INTERVAL 7 DAY) AND NOW()  GROUP BY EMAIL ORDER BY last_visit DESC

您可以添加一个子查询来对每个组中的行进行编号,然后 select 从该子查询中仅对每个组中的第一行进行编号:

SELECT EMAIL, VISIT FROM (
    SELECT EMAIL, VISIT, ROW_NUMBER() OVER (PARTITION BY EMAIL ORDER BY VISIT DESC) AS 'RowNumber' 
    FROM table 
    WHERE VISIT>DATE_SUB(NOW(), INTERVAL 7 DAY)
) T1
WHERE RowNumber=1

我向您推荐此代码:‌

SELECT
    EMAIL
FROM `table_name`
WHERE
    VISIT BETWEEN(NOW() - INTERVAL 7 DAY) AND NOW()
GROUP BY
    EMAIL
ORDER BY
    MAX(VISIT)
DESC;