You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Oracle中distinct on的等价实现及指定SQL查询转译方法

Oracle替代PostgreSQL DISTINCT ON的方案及SQL转译

等价实现逻辑

PostgreSQL的DISTINCT ON (字段)是按指定字段分组,保留每组内的第一条记录。Oracle没有原生支持这个语法,最常用的替代方案是窗口函数ROW_NUMBER():

  • 用PARTITION BY指定要去重的字段(对应DISTINCT ON后的字段)
  • 用ORDER BY定义每组内的排序规则(决定保留哪一行,无特定需求时可任选字段排序)
  • 最后筛选出每组内序号为1的记录,即可实现和DISTINCT ON一致的效果

转译后的Oracle兼容SQL

假设原SQL的表关联逻辑为交易表t关联客户表c(关联条件示例:t.customer_id = c.customer_id),转译后的完整SQL如下:

SELECT transactionId, transactionStatus, customerId, customerName
FROM (
    SELECT 
        t.transaction_id AS transactionId,
        t.transaction_status AS transactionStatus,
        c.customer_id AS customerId,
        c.customer_name AS customerName,
        ROW_NUMBER() OVER(PARTITION BY t.transaction_id ORDER BY t.transaction_id) AS rn
    FROM t
    JOIN c ON t.customer_id = c.customer_id
)
WHERE rn = 1;

补充说明

如果需要保留每组内符合特定规则的行(比如最新交易状态的记录),只需修改ORDER BY后的字段即可,例如改成ORDER BY t.transaction_date DESC。

内容的提问来源于stack exchange,提问作者user19471184

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 11:10:40