如何选择sql中日期最大的行

brtdzjyr  于 2021-07-27  发布在  Java
关注(0)|答案(3)|浏览(372)

您好,我对数据库有以下查询:

select DISTINCT(CO_GID),
max(last_modified ) as DIA,
TRX_INI_FREQUENCY as TRX
from C_BSC_TRX ,UTP_COMMON_OBJECTS 
where (OBJ_GID = CO_GID)  
and (CO_GID LIKE '114481%')
GROUP BY CO_GID,TRX_INI_FREQUENCY

CO_GID   DIA           TRX
114481  07/11/18       null 
114481  27/10/18        49
114481  22/06/20        96

问题是,我只希望返回带有最新日期的行:在这种情况下是06-22-2020,而group by阻止了我,因为我必须将trx\u ini\u频率放在group by中
我想要的是:

CO_GID   DIA           TRX
114481  22/06/20        96
rhfm7lfc

rhfm7lfc1#

你可以用 keep 获取的最后一个值 trx :

select CO_GID,
       max(last_modified) as DIA,
       max(TRX_INI_FREQUENCY) keep (dense_rank first order by last_modified desc) as TRX
from C_BSC_TRX JOIN
    UTP_COMMON_OBJECTS 
    on OBJ_GID = CO_GID and CO_GID LIKE '114481%'
group by CO_GID;

笔记:
不要在句子中使用逗号 FROM 条款。
始终使用适当的、明确的、标准的、可读的 JOIN 语法。
限定列名!不清楚哪些列来自哪些表。

5lhxktic

5lhxktic2#

根据您使用的是什么,添加并选择Top1和order by dia desc

tv6aics1

tv6aics13#

select top 1 DISTINCT(CO_GID),
max(last_modified ) as DIA,
TRX_INI_FREQUENCY as TRX
from C_BSC_TRX ,UTP_COMMON_OBJECTS 
where (OBJ_GID = CO_GID)  
and (CO_GID LIKE '114481%')
GROUP BY CO_GID,TRX_INI_FREQUENCY
Order by DIA desc

相关问题