[英]how to update a table with the most frequent value
I have an update query that should update a field with the most frequent values from another table this is how i do it in postgreSQL 我有一个更新查询应该更新一个具有来自另一个表的最频繁值的字段这是我在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
)
this works fine in postgresql , i want to do the same query in Oracle using rownum =1 but I have several issues : 这在postgresql中运行正常,我想在Oracle中使用rownum = 1进行相同的查询,但我有几个问题:
T2.COLUMN_A = T1.COLUMN_A
gives an error that T1.COLUMN_A invalid identifier) T2.COLUMN_A = T1.COLUMN_A
给出错误,即T1.COLUMN_A无效标识符) How can i do this in oracle? 我怎么能在oracle中这样做? what i want is that T1.COLUMN_B be filled with the most frequent common value of COLUMN_B FROM T2 for each COLUMN_A.
我想要的是T1.COLUMN_B为每个COLUMN_A填充COLUMN_B FROM T2的最常见公共值。
Thank you for any help or suggestion 感谢您的任何帮助或建议
I'm pretty sure there is some much less complicated way to do this but this should be good starting point and should work both in Oracle and in Postgres 我很确定有一些不那么复杂的方法可以做到这一点,但这应该是一个很好的起点,应该在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)
)
)
)
This can be done in Oracle uses analytic functions; 这可以在Oracle中使用分析函数来完成; don't know whether the same code would work in PostgreSQL.
不知道相同的代码是否适用于PostgreSQL。
Creating a target table: 创建目标表:
SQL> create table t23
2 as select deptno, cast (null as number(7,2)) max_sal from dept
3 /
Table created.
SQL>
Now, the update: 现在,更新:
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>
Here is the outcome: 结果如下:
SQL> select * from t23
2 /
DEPTNO MAX_SAL
---------- ----------
10 5000
20 3000
30 3750
40
50 4500
60
6 rows selected.
SQL>
Just to confirm the results... 只是为了确认结果......
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.