SQL: self JOIN top 1 from table SELECTs? (or better way of doing it...)
This has probably been discussed before (or it's too simple), but I can't find an easy answer: How should this be done: select the (single) earliest future date and most recent date per 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 |
I was thinking along the lines of the following, but I have the feeling that this is rather complicated/bad syntax, and I haven't figured out how to limit to single results (i.e. most recent/nearest in future). Any suggestions?
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
I think you could use:
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
It's unclear what database you're working with - TOP is TSQL/SQL Server syntax only (2000+), while NOW as NOW()
is supported by MySQL and PostgreSQL... CURRENT_TIMESTAMP is ANSI, and supported by all.
why wouldn't this work?
select min(date) past_date,max(DATE)future_date
from t1
HAVING MIN(date) < CURRENT_TIMESTAMP AND MAX(DATE) < CURRENT_TIMESTAMP
group by id
精彩评论