在加入时需要SQL根据我的特定列获取最大行数

时间:2014-10-09 03:56:41

标签: sql oracle

您好我有Oracle查询示例及其各自的输出

select t1.account,t1.ID ,t2.NAME , t2.CHILDAC from t1,t2 where t1.ID = t2.ID;

输出示例

ACCOUNT       ID        NAME    CHILDAC
9001          1         xxx      root1
9006          3         xxy      root1
9003          4         xra      root1
9008          5         xii      root2
9011          6         xxt      root2
9045          7         xxy      root3
9089          8         xxu      root3
9033          10        xss      root4

我的预期输出如下,这意味着我需要返回 CHILDAC 列的唯一值行,最多 ID

预期

ACCOUNT       ID        NAME    CHILDAC
9003          4         xra      root1
9011          6         xxt      root2
9089          8         xxu      root3
9033          10        xss      root4

请为我提供上述场景的SQL

1 个答案:

答案 0 :(得分:1)

您可以将row_number()与子查询一起使用:

select *
from (
    select t1.account, t1.ID, t2.NAME, t2.CHILDAC, 
           row_number() over (partition by t2.Childac order by t1.id desc) rn
    from t1 
        join t2 on t1.ID = t2.ID
) t
where rn = 1