聽起來像是keep dense_rank
工作:
select min(user_id) keep (dense_rank last order by coalesce(login_date, create_date))
as user_id,
login_id
from list_users
group by login_id
order by user_id;
的last
保持與最新的登錄記錄/創建日期; coalesce()
首先獲取登錄日期,如果該值爲null(或者您可以使用nvl()
而不是當然),則會返回到創建日期。你也可以做first
並按desc
排序 - 結果是一樣的(如果沒有空值,看起來應該不是),但last
感覺更直觀,當你想要我認爲最新的日期時。 演示使用一個CTE數據:
with list_users(user_id, login_id, create_date, login_date) as (
select 101, 'test1', date '2016-04-24', null from dual
union all select 102, 'test1', date '2016-04-24', date '2016-04-29' from dual
union all select 103, 'test2', date '2016-04-25', null from dual
union all select 104, 'test2', date '2016-04-26', null from dual
union all select 105, 'test3', date '2016-04-27', date '2016-04-28' from dual
union all select 106, 'test3', date '2016-04-27', date '2016-04-29' from dual
union all select 107, 'test4', date '2016-04-28', date '2016-04-29' from dual
)
select min(user_id) keep (dense_rank last order by coalesce(login_date, create_date))
as user_id,
login_id
from list_users
group by login_id
order by user_id;
USER_ID LOGIN
---------- -----
102 test1
104 test2
106 test3
107 test4
並與修改後的數據:
with list_users(user_id, login_id, create_date, login_date) as (
select 101, 'test1', date '2016-04-24', null from dual
union all select 102, 'test1', date '2016-04-24', date '2016-04-29' from dual
union all select 103, 'test2', date '2016-04-25', null from dual
union all select 104, 'test2', date '2016-04-26', null from dual
union all select 105, 'test3', date '2016-04-27', date '2016-04-28' from dual
union all select 106, 'test3', date '2016-04-27', date '2016-04-29' from dual
union all select 107, 'test4', date '2016-04-28', date '2016-04-29' from dual
union all select 987, 'test5', date '2016-04-29', null from dual
union all select 109, 'test5', date '2016-04-29', null from dual
union all select 108, 'test5', date '2016-04-29', date '2016-04-29' from dual
)
select min(user_id) keep (dense_rank last order by coalesce(login_date, create_date))
as user_id,
login_id
from list_users
group by login_id
order by user_id;
USER_ID LOGIN
---------- -----
102 test1
104 test2
106 test3
107 test4
108 test5
會發生什麼,如果用戶登錄兩次在同一天?你想保留哪一個? –
應用程序中存在一個錯誤,導致上述情況。基本上我需要保留最新的記錄並清理其他記錄。 – user2893856