查找最小和最大日期 SQL

Finding min and max dates SQL

我想创建一个查询,只查找最早和最新 registration_date 成员的详细信息。到目前为止我有

SELECT member_id, UPPER(name), registration_date 
from db.member WHERE registration_date >=
'2012-01-01' 

我不确定如何找到 min/max 但我只是用设定的日期 2012-01-01

测试它

所以查询应该只返回两个结果 - min/max

提前致谢

你可以在子查询中得到 min , max 日期然后得到结果。

select member_id, upper(name), registration_date
from db.member
cross join (
       select min(registration_date) as minDate, max(registration_date) as maxDate
       from db.member ) t
where registration_date in ( t.minDate, t.maxDate)

或者您可以使用 inunion

select member_id, upper(name), registration_date
from db.member
where registration_date in  (
       select min(registration_date) 
       from db.member
       union 
       select max(registration_date) as maxDate
       from db.member ) 

select min(date Column),max(date Column) from table;

像下面这样的东西,虽然有点重子查询,但可能会让您最接近您的需要。根据您的 SQL(Oracle、SQLServer、MySQL 等...)的风格,您可以限制 member_id 在 IN 结果中选择的子查询设置子查询。

select member_id, Upper(name) AS name, registration_date 
from db.member 
where member_id in
(
    select Min(member_id) 
    from db.member
    where registration_date =
    (
        select Min(registration_date)
        from db.member
    )
    union all
    select Max(member_id) 
    from db.member
    where registration_date = 
    (
        select Max(registration_date)
        from db.member
    )
)
order by registration_date desc;