如何更新具有最常值的表

时间:2011-08-09 13:33:46

标签: sql oracle

我有一个更新查询,应该使用另一个表中最频繁的值更新字段 这就是我在postgreSQL中的表现方式

UPDATE TABLE1 T1 
SET COLUMN_B = (SELECT COLUMN_B
                         FROM 
                         (SELECT COLUMN_A,COLUMN_B, COUNT(1) AS FREQUENCY
                                 FROM TABLE2 T2
                                GROUP BY COLUMN_A,COLUMN_B
                                 ORDER BY COLUMN_A,FREQUENCY DESC) QUERY1
                          WHERE QUERY1.COLUMN_A= T1.COLUMN_A

                    GROUP BY COLUMN_A,COLUMN_B,FREQUENCY
                    ORDER BY FREQUENCY DESC LIMIT 1
                   )

这在postgresql中工作正常,我想在Oracle中使用rownum = 1进行相同的查询,但我有几个问题:

  1. 我无法在更新选择中加入ORDER BY
  2. 如果我决定将顺序放在嵌套选择(QUERY1)中,嵌套选择不理解对表T1的引用(T2.COLUMN_A = T1.COLUMN_A给出错误,即T1.COLUMN_A无效标识符)
  3. 我怎样才能在oracle中这样做?我想要的是T1.COLUMN_B为每个COLUMN_A填充COLUMN_B FROM T2的最常见公共值。

    感谢您提供任何帮助或建议

2 个答案:

答案 0 :(得分:2)

我很确定有一些不太复杂的方法可以做到这一点,但这应该是一个很好的起点,并且应该在Oracle和Postgres中都有用

UPDATE TABLE1 T1
SET COLUMN_B = 
select COLUMN_B from (
(SELECT DISTINCT COLUMN_A, COLUMN_B
    FROM TABLE2 T2
    WHERE T2.COLUMN_A= T1.COLUMN_A
    GROUP BY COLUMN_A, COLUMN_B
    HAVING COUNT(1) = (
        SELECT MAX(CNT) FROM (
            SELECT COLUMN_B, COUNT(1) AS CNT
            FROM TABLE2 T3
            WHERE T3.COLUMN_A= T2.COLUMN_A)
        )
    )
)

答案 1 :(得分:2)

这可以在Oracle中使用分析函数来完成;不知道相同的代码是否适用于PostgreSQL。

创建目标表:

SQL> create table t23
  2    as select deptno, cast (null as number(7,2)) max_sal from dept
  3  /

Table created.
SQL> 

现在,更新:

SQL> update t23
  2  set max_sal = ( select sal from
  3                   ( select deptno, sal
  4                     , row_number() over (partition by deptno order by sal desc) rn
  5                      from emp )
  6                 where rn = 1
  7                 and deptno = t23.deptno )
  8  /

6 rows updated.

SQL>

结果如下:

SQL> select * from t23
  2  /

    DEPTNO    MAX_SAL
---------- ----------
        10       5000
        20       3000
        30       3750
        40
        50       4500
        60

6 rows selected.

SQL> 

只是为了确认结果......

SQL> select deptno, max(sal)
  2  from emp
  3  where sal is not null
  4  group by deptno
  5  order by deptno
  6  /

    DEPTNO   MAX(SAL)
---------- ----------
        10       5000
        20       3000
        30       3750
        50       4500

SQL>