仅选择一个具有最新登录日期的组

时间:2019-03-20 05:43:13

标签: sql oracle select group-by

我正在尝试仅获取具有最大登录日期的1个组。

user_ID    Group       Login_Date
Mulan      Flower        4/4/2017
Mulan      Badminton   11/20/2015
Mulan      Flower      11/20/2015

我的代码

select distinct group from table t
where t.user_ID = 'Mulan'
and t.Login_Date = (select max (t2.Login_Date)
                      from table t2
                      where t.user_ID = t2.user_ID
                        and t2.Login_date <= sysdate)

结果

Flower
Badminton

所需的输出

Flower

尽管有2朵花,但我要确保获得的花是具有最新Login_Date(即4/4/2017)的花,并且输出应仅返回1值。

4 个答案:

答案 0 :(得分:1)

-- Oracle: first/last functions
with s (user_ID, grp, Login_Date) as (
select 'Mulan', 'Flower'   , to_date('4/4/2017'  , 'mm/dd/yyyy') from dual union all
select 'Mulan', 'Badminton', to_date('11/20/2015', 'mm/dd/yyyy') from dual union all
select 'Mulan', 'Flower'   , to_date('11/20/2015', 'mm/dd/yyyy') from dual)
select
user_id,
max(grp) keep (dense_rank last order by login_date) as grp,
max(login_date) as log_date
from s
group by user_id;

USER_ GRP       LOG_DATE
----- --------- -------------------
Mulan Flower    2017-04-04 00:00:00

回答其他问题:

with s (user_ID, grp, Login_Date) as (
select 'Mulan', 'Flower'   , to_date('4/4/2017'  , 'mm/dd/yyyy') from dual union all
select 'Mulan', 'Badminton', to_date('11/20/2015', 'mm/dd/yyyy') from dual union all
select 'Mulan', 'Flower'   , to_date('11/20/2015', 'mm/dd/yyyy') from dual)
select
max(grp) keep (dense_rank last order by login_date) as grp
from s
group by user_id;

GRP
---------
Flower

答案 1 :(得分:0)

只需删除and t2.Login_date <= sysdate条件

select  group from table t
where t.user_ID = 'Mulan' -- you dont need this if user is only Mulan
and t.Login_Date = (select max (t2.Login_Date)
                      from table t2
                      where t.user_ID = t2.user_ID
                        )

输出

USER_ID     GRP     LOGIN_DATE
Mulan   Flower  04-APR-17

或使用row_number()

  with cte as
  (
  select t.*,row_number()over(partition by user_ID order by Login_Date desc) rn
  from table t
 ) select * from cte where rn=1

输出

USER_ID     GRP     LOGIN_DATE
Mulan   Flower  04-APR-17

demo link for both version

答案 2 :(得分:0)

请尝试这个。而且您的sysdate可能会回到当前日期。

select distinct top 1 group from table t
where t.user_ID = 'Mulan'
and t.Login_Date = (select max (t2.Login_Date)
                      from table t2
                      where t.user_ID = t2.user_ID
                        and t2.Login_date <= sysdate)

OR

 select distinct top 1 group from table t
    where t.user_ID = 'Mulan'
    and t.Login_Date = (select max (t2.Login_Date)
                          from table t2
                          where t.user_ID = t2.user_ID
                        )

答案 3 :(得分:0)

这应该是简单的解决方案

this.state.timeSlotItemSelected