我有以下查询:
SELECT distinct person, address, from_date, to_date
FROM db
WHERE '2000-01-01' BETWEEN from_date AND to_date
这很好,但是它在2000年1月1日带回了一些有多个地址的人。我想只选择具有最大to_date的地址。
即查询返回:
person-------------address--------from_date--------to_date
1------------------34-------------1999-06-12-------2000-04-04
1------------------27-------------1999-06-12-------2000-12-12
我想只选择第二行。
以下是否足够?
SELECT distinct person, address,from_date, MAX(to_date)
FROM db
WHERE '2000-01-01' BETWEEN from_date AND to_date
答案 0 :(得分:4)
查询可能类似(但可以进一步简化):
SELECT db.person, address, from_date,db.to_date
FROM db, (SELECT person, max(to_date) to_date
FROM db
GROUP BY person) db_max
WHERE '2000-01-01' BETWEEN db.from_date AND db.to_date
AND db.to_date = db_max.to_date
AND db.person = db_max.person;
答案 1 :(得分:1)
SELECT person, address,from_date, to_date
FROM db db_outer
WHERE '2000-01-01' BETWEEN from_date AND to_date
AND EXISTS (SELECT 1
FROM db db_inner
WHERE db_outer.person = db_inner.person
GROUP BY db_inner.person
HAVING MAX(db_inner.to_date) = db_outer.to_date)
答案 2 :(得分:1)
你需要一个子查询:http://allenbrowne.com/subquery-01.html是最好的解释,子查询可以有一个订单,因为你有一个“顶部”