簡體   English   中英

如何在 Oracle DB 中使用 max(Date) 和 Distinct。 我想在一天內最后插入數據

[英]How to use max(Date) and Distinct in Oracle DB. I would like to get data inserted very last within a day

我正在尋找一種獲取數據的方法。 按最新日期 在同一天按 UserId

UserId,Value1,Date
1, 2030,2020–09-07 10:58:58
1, 2020,2020–09-07 05:58:28
1, 2050,2020–09-08 19:58:28
2, 3000,2020–09-07 10:58:18
2, 2001,2020–09-06 10:58:55
3, 2400,2020–09-08 10:28:53
4, 2400,2020–09-07 13:28:53

例如

where Date >=  trunc(TO_DATE(’20200907’,’YYYYMMDD’))   and Date < trunc(TO_DATE(’20200908’,’YYYYMMDD’))  

理想結果

UserId,Value
1,2050 
2,3000
4,2400

選擇 UserId, value 我應該使用什么?

 max(Date) ? Distinct userId ?  Group  by userId?

如果value是您想要的唯一列,那么您可以使用keep

select userid, max(value1) keep(dense_rank last order by dt) value1
from mytable
where dt >= date '2020-09-07' and dt < date '2020-09-08'
group by userid
order by userid

筆記:

  • 這使用標准date語法而不是to_date()來構建文字日期

  • date是 Oracle 中的保留字,因此不是列名的好選擇; 我在查詢中將其重命名為dt

如果你想在結果集中有更多的列,那么使用窗口函數過濾更合適:

select t.*
from (
    select t.*, row_number() over(partition by userid order by dt desc) rn
    from mytable t
    where dt >= date '2020-09-07' and dt < date '2020-09-08'
) t
where rn = 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM