2

我有以下查询:

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
4

3 回答 3

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;
于 2013-03-19T11:37:22.723 回答
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)
于 2013-03-19T11:36:17.623 回答
1

你需要一个子查询:http ://allenbrowne.com/subquery-01.html是最好的解释,子查询可以有一个顺序,因为你有一个“顶部”

于 2013-03-19T11:38:28.603 回答