![](/img/trans.png)
[英]Copy a column to another column within a same table in oracle db. Do I need to specify which data goes where?
[英]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.