gpt4 book ai didi

mysql - 按多列和时间跨度对 MYSQL 结果进行分组

转载 作者:行者123 更新时间:2023-11-29 06:06:03 25 4
gpt4 key购买 nike

如何从今天开始倒数,每 7 天为每个 UID 选择一个最近的 NID

如果今天是7月11日,则如下表

+-----+------------+-----+
| NID | timestamp | UID |
+-----+------------+-----+
| 1 | 1341719851 | 8 | //July 7
| 2 | 1341115051 | 8 | //July 1
| 3 | 1341547051 | 8 | //July 6
| 4 | 1341719851 | 8 | //July 8
| 5 | 1341979051 | 8 | //July 11
| 6 | 1341806251 | 9 | //July 9
| 7 | 1341460651 | 9 | //July 5
| 8 | 1341892651 | 9 | //July 10
+-----+------------+-----+

将输出:

+-----+------------+-----+
| NID | timestamp | UID |
+-----+------------+-----+
| 2 | 1341115051 | 8 | //July 1
| 5 | 1341979051 | 8 | //July 11
| 8 | 1341892651 | 9 | //July 10
+-----+------------+-----+

在过去 7 天内,每个用户的最新 NID'5''8'(在前 7 天内) ,最近的 NID'2',依此类推...

我假设 Group By 可以解决问题;但我不知道从哪里开始。

更新

根据最重要的答案,这是有效的查询:

SELECT nid, timestamp, uid, weeks_ago
FROM (
SELECT nid, timestamp, uid, FLOOR(
(UNIX_TIMESTAMP()- timestamp)/604800
) weeks_ago
FROM `table`
ORDER BY timestamp DESC
) x
GROUP BY uid, weeks_ago

最佳答案

select nid, max(timestamp), uid, weeks_ago
from (select nid, timestamp, uid, floor(datediff(now(), from_unixtime(timestamp))/7) weeks_ago
from mytable) x
group by nid, uid, weeks_ago

关于mysql - 按多列和时间跨度对 MYSQL 结果进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11444990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com