Alw*_*ner 1 sql oracle date greatest-n-per-group
我是SQL的新手,因此这个问题 -
DATE我的表中有一列,我的查询应该用最新的值获取值DATE.我意识到我可以通过以下任何方式实现 -
SELECT TRUNC(MAX(createddatetm)) cdt
FROM (SELECT TO_TIMESTAMP(TO_CHAR(createddate, 'Month dd, yyyy hh:mi AM'), 'Month dd, yyyy hh:mi AM') as createddatetm
FROM comments WHERE commentid = '1234');
SELECT trunc(MAX(TO_TIMESTAMP(to_char(createddate, 'Month dd, yyyy hh:mi AM'), 'Month dd, yyyy hh:mi AM')))
FROM (SELECT createddate
FROM comments
WHERE commentid = '1234');
SELECT TRUNC(MAX(createddatetm)) cdt
FROM (SELECT TO_CHAR(createddate, 'Month dd, yyyy hh:mi AM') as createddatetm
FROM comments WHERE commentid = '1234');
SELECT trunc(MAX(to_char(createddate, 'Month dd, yyyy hh:mi AM')))
FROM (SELECT createddate
FROM comments
WHERE commentid = '1234');
这是我的问题 -有没有其他更简单的方法可以实现这一目标?或者我应该使用我提到过的任何一种吗?此外,这些查询在性能方面是否存在差异?我不认为有,但我需要确认一次.
为什么要将日期转换为varchar以将其再次转换回日期/时间戳?您可以只比较/使用存储在数据库中的日期值.
使用窗口函数可以轻松解决您的问题:
select *
from (
select c.*,
row_number() over (order by createddate desc) as rn
from comments
where commentid = 1234
) t
where rn = 1;
Run Code Online (Sandbox Code Playgroud)
或者使用 max()
select *
from (
select c.*,
max(createddate) over () as max_createddate
from comments
where commentid = 1234
) t
where max_createddate = createddate;
Run Code Online (Sandbox Code Playgroud)
或者如果你需要多个有价值的价值:
select *
from (
select c.*,
row_number() over (partition by commentid order by createddate desc) as rn
from comments
) t
where rn = 1;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1772 次 |
| 最近记录: |