pgsql如何计算两列中的值

时间:2018-01-09 17:34:47

标签: postgresql

我有2张桌子

第一张表:

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 columns job1 and job2出现的次数,并将该总值更新为second table column "jobs"

3 个答案:

答案 0 :(得分:2)

您需要首先解除对第一个表的转动,以便您可以对作业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;

答案 1 :(得分:0)

您可以使用相关更新。

UPDATE table2 t2
SET    jobs = (SELECT Count(*) AS job_count
               FROM   (SELECT job1 id
                       FROM   table1
                       UNION ALL
                       SELECT job2 id
                       FROM   table1) t1
               WHERE  t1.id = t2.id
               GROUP  BY id);  

DEMO

答案 2 :(得分:0)

又一个解决方案:

update table2 set
  jobs = (
    select sum(case when job1 = job2 then 2 else 1 end)
    from table1
    where table2.id = job1 or table2.id = job2)