更新子请求并限制 rownum

问题描述

我写了这个查询

UPDATE artpxvtemagtemp a
    SET
    origineprix = 'CEN',pxvente = (
        SELECT
            ap.pxvtrpublic
        FROM
            artpxvte   ap
            JOIN article    ar ON ar.idarticle = ap.idarticle
        WHERE
            ap.idarticle = a.idarticle
            AND a.unite = ap.unite
            AND ap.isdegressif = 0
            AND ap.idtarifvte = 'T00002'
            AND ap.datedebut <= pdateappli
            AND ( ap.datefin IS NULL OR pdateappli < ( ap.datefin + 1 ) )
    );

但有时子查询给出不止一个结果,所以更新失败。 我想对结果进行排序并选择子查询的第一个结果进行更新。 所以我这样做:

UPDATE artpxvtemagtemp a
SET
    origineprix = 'CEN',pxvente = (
        SELECT
            pxvtrpublic
        FROM 
        (
        SELECT
            ap.pxvtrpublic
        FROM
            artpxvte   ap
            JOIN article    ar ON ar.idarticle = ap.idarticle
        WHERE
            ap.idarticle = a.idarticle
            AND a.unite = ap.unite
            AND ap.isdegressif = 0
            AND ap.idtarifvte = 'T00002'
            AND ap.datedebut <= pdateappli
            AND ( ap.datefin IS NULL
                    OR pdateappli < ( ap.datefin + 1 ) )
        ORDER BY 
            CASE WHEN ap.datefin IS NULL THEN 0 ELSE 1 END ASC,ap.datefin DESC,ap.datedebut DESC
        )
        where rownnum <= 1
    );

它不起作用,因为别名 a 丢失了,所以我必须为 rownnum 添加一个额外的子查询

错误 sql : ORA-00904: "A"."UNITE" : identificateur non valide 00904. 00000 - "%s: 无效标识符"

在 Oracle 12C 中,我不需要子查询获取前 N 行,但我有一个旧版本的 Oracle,所以我不能使用它。

如何让别名 a 为人所知?

解决方法

改为使用聚合:

pxvente = (select max(ap.pxvtrpublic) keep (dense rank first
                                            order by case when ap.datefin is null then 0 else 1 end,ap.datefin desc,ap.datedebut desc
                                           )
            from . . .