我有两张 table
第一个表:
num | job1 | job2
--------------------
1 14 12
2 23 14
3 3 12
4 21 3
5 6 8
第二个:
id | jobs
------------
3
12
14
21
23
etc...
我需要计算 second table's id
在 first table,s 出现了多少次
列 job1 和 job2
并将总值更新到 second table column "jobs"
最佳答案
您需要先取消对第一个表的透视,以便您可以对作业 ID 进行分组:
select t.job_id, count(*) as num_jobs
from first_table, unnest(array[job1, job2]) as t(job_id)
group by t.job_id;
使用返回的样本数据:
job_id | num_jobs
-------+---------
21 | 1
6 | 1
12 | 2
23 | 1
14 | 2
3 | 2
8 | 1
现在这可以用来更新 second_table:
update second_table
set jobs = x.num_jobs
from (
select t.job_id, count(*) as num_jobs
from first_table, unnest(array[job1, job2]) as t(job_id)
group by t.job_id
) x
where x.job_id = id;
关于postgresql - pgsql如何计算两列的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48173770/