postgresql - pgsql如何计算两列的值

标签 postgresql

我有两张 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 idfirst 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/

相关文章:

php - 如何防止某人使用促销代码两次?

DJANGO/Heroku 未保存到数据库 POSTGRES

postgresql - 为什么设置非空约束时不使用默认值?

ruby-on-rails - 如何在原始查询(rails + postgres)中使用动态 ids 数组?

postgres 数组的正则表达式

sql - Postgres 中多个数组的平均值

ruby-on-rails-3 - 如何使用 Datamapper 迁移调整 postgreSQL 数据库中的列长度?

sql - 在 Postgres 中,使用 "attempts"时是否可以使用 ROLLBACK TO SAVEPOINT 来实现 "FOR UPDATE SKIP LOCKED"?

PostgreSQL BEFORE INSERT 触发器在并发环境中的锁定行为

postgresql - 在 pyspark 中使用 jdbc jar