gpt4 book ai didi

mysql - 加入同一个表的子集

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

我正在尝试将一个表连接到其自身的一个子集,但遇到了问题。我的输入包含一个 ID 和一个日期,如下所示:

 2013-10-14 eca02319d91421445f82d570960c5d0c

2013-10-15 eca02319d91421445f82d570960c5d0c

2013-10-16 eca02319d91421445f82d570960c5d0c

2013-10-17 eca02319d91421445f82d570960c5d0c

2013-10-19 eca02319d91421445f82d570960c5d0c

2013-10-21 eca02319d91421445f82d570960c5d0c

我的目标是确定每个日期的相同 id 的最后一个日期,例如:

     Date          ID                                 Last Date
2013-10-21 eca02319d91421445f82d570960c5d0c 2013-10-19

2013-10-19 eca02319d91421445f82d570960c5d0c 2013-10-17
etc.

使用以下 SQL,我得到以下输出:

select a.Day,a.entity, b.Day from Visitor a
LEFT OUTER JOIN Visitor b
on a.entity = b.entity
and b.day < a.day
where b.day is not null

output

2013-10-21 eca02319d91421445f82d570960c5d0c 2013-10-14

2013-10-21 eca02319d91421445f82d570960c5d0c 2013-10-15

2013-10-21 eca02319d91421445f82d570960c5d0c 2013-10-17

2013-10-21 eca02319d91421445f82d570960c5d0c 2013-10-19

2013-10-19 eca02319d91421445f82d570960c5d0c 2013-10-14

2013-10-19 eca02319d91421445f82d570960c5d0c 2013-10-15

对于 a.day 的每个实例只获取一条记录以及按降序处理 b.day 需要什么?

提前致谢!

最佳答案

尝试这样的事情:

SELECT distinct a.date, a.id, (select d.date from data d
where a.date > d.date AND a.id = d.id
order by d.date desc limit 1) as last_date
FROM data a where (select d.date from data d
where a.date > d.date AND a.id = d.id
order by d.date desc limit 1) is not null
ORDER by a.date desc;

SQL Fiddle

关于mysql - 加入同一个表的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19532575/

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