sql - PostgreSQL 在函数中获得最新记录
问题描述
我有一个名为 cdr_get_call_log 的函数。我正在从这个函数中获取我的数据。正如您在示例数据记录中看到的那样,3 号和 4 号数据记录具有相同的 source_caller_id 和同一天,但时间不同。所以我想如果我的数据中有相同的 source_caller_id 我只想记录 start_time 是最新的
select source_caller_id,destination_dn,recording_url,start_time
from (
select *
from cdr_get_call_log
where destination_type=0
and talking_duration is not null
and source_caller_id not like 'Ext%'
and source_caller_id like '0%'
and destination_dn in('628','627','629','630','631','626','600','632')
and source_caller_id<> '09903114243'
and subrow_desc_number='1'
and trim(recording_url)<> ''
) as a
表结构
| source_caller_id | destination_dn | recording_url | start_time |
|------------------|----------------|--------------------|-----------------------|
| 1.05356785544 | 627 | [627]/20180230.wav | 01/12/2018 11.12:39 |
| 2.05551165244 | 632 | [632]/20180230.wav | 04/12/2018 09.12:39 |
| 3.05556665544 | 621 | [627]/20180230.wav | 06/12/2018 05.12:39 |
| 4.05556665544 | 626 | [627]/20180230.wav | 06/12/2018 05.15:39 |
解决方案
您可以使用distinct on
:
with q as (<your query here>)
select distinct on (caller_id, date_trunc('day', start_time)) q.*
from q
order by caller_id, date_trunc('day', start_time), start_time desc;
推荐阅读
- azure - Azure 流分析 - 加入两个流式源
- node.js - Node.JS 中的异步函数调用 SQL Server 无法正常工作
- c - 带有for循环和if语句错误的斐波那契数字代码
- java - 将 DynamoDB 文档解析为 Map
在爪哇 - java - 骆驼节流和相关表达式
- elasticsearch - Elasticsearch 缺少结果和不正确的排序
- angular - Angular 中的 XML 编辑器
- powerbi - Power BI - 为成千上万的人添加切片器
- powershell - Google 扩展程序可以搜索您的操作系统吗?
- reactjs - 反应与 Nextjs 的光滑兼容性