之前可能已经讨论过这个问题(或者说太简单了),但我找不到一个简单的答案:如何做到这一点:选择(单个)最早的未来日期和每个id的最近日期?
t1: ==?==> (earliest) (most recent)
|id|date(DESC)| |id|future_date | past_date |
+==+==========+ +==+=============+===============+
|1 | d1 | | 1| d1 | d3 |
|2 | d2 | | 2| d2 | d6 |
(<==now) | 3| | d4 |
|1 | d3 |
|3 | d4 |
|1 | d5 |
|2 | d6 |
我正在考虑以下几点,但我觉得这是相当复杂/错误的语法,我还没有想出如何限制单个结果(即最近/最近的)。有什么建议吗?
SELECT t_1.id,t_1.date AS future_date,t_2.date AS past_date
FROM (SELECT * FROM t1 WHERE t1.date>CURRENT_TIMESTAMP) t_1
LEFT OUTER JOIN
(SELECT TOP 1 * FROM t1 WHERE t1.date<CURRENT_TIMESTAMP) t_2
ON t_1.id=t_2.id
答案 0 :(得分:0)
我认为你可以使用:
SELECT x.id,
MIN(y.date) AS future_date,
MAX(z.date) AS past_date
FROM (SELECT DISTINCT t.id
FROM YOUR_TABLE t) x
LEFT JOIN YOUR_TABLE y ON y.id = x.id
AND y.date > CURRENT_TIMESTAMP
LEFT JOIN YOUR_TABLE z ON z.id = x.id
AND z.date < CURRENT_TIMESTAMP
GROUP BY x.id
目前还不清楚你正在使用什么数据库--TOP只有TSQL / SQL Server语法(2000+),而MySQL和PostgreSQL支持NOW为NOW()
... CURRENT_TIMESTAMP是ANSI,并且受到支持所有
答案 1 :(得分:0)
为什么这不起作用?
select min(date) past_date,max(DATE)future_date
from t1
HAVING MIN(date) < CURRENT_TIMESTAMP AND MAX(DATE) < CURRENT_TIMESTAMP
group by id