从一个表中的列中选择一个特定的数字到另一个表中

时间:2018-06-28 10:50:46

标签: postgresql psql pgadmin

我有一个名为processtime的表

id  | task1id | task1occ | task1time | task2id | task2occ | task2time | task3id | task3occ | task3time | task4id | task4occ | task4time | task5id | task5occ | task5time 
----+---------+----------+-----------+---------+----------+-----------+---------+----------+-----------+---------+----------+-----------+---------+----------+-----------
 10 |       9 |        0 |       300 |         |          |           |         |          |           |         |          |           |         |          |          
  7 |       5 |        1 |        20 |       6 |        1 |        45 |       1 |        0 |        60 |         |          |           |         |          |          
  9 |       6 |        1 |        45 |       7 |        1 |       120 |       2 |        0 |       110 |         |          |           |         |          |          
  8 |       5 |        1 |        20 |       6 |        1 |        45 |       3 |        1 |       200 |       1 |        0 |        60 |       4 |        1 |       300

和名为test1的表

 id | task1time | task2time | task3time | task4time | task5time 
----+-----------+-----------+-----------+-----------+-----------

我要尝试的是,如果processtime中的任何occ列中的值都为0,则任务时间将显示在test1时间列中。

因此test1表应如下所示。 :

id  | task1time | task2time | task3time | task4time | task5time 
----+-----------+-----------+-----------+-----------+----------- 
 10 |    300    |           |           |           |     
 7  |           |           |     60    |           |
 9  |           |           |     60    |           |
 8  |           |           |           |     60    |

我尝试使用OR和AND函数,但是它们不起作用,我当时想IF函数可能起作用,但是不知道从何处开始

非常感谢

戴夫

1 个答案:

答案 0 :(得分:1)

这是一个基本查询,应按您的预期工作:

SELECT
    id,
    CASE WHEN task1occ = 0 THEN task1time END AS task1time,
    CASE WHEN task2occ = 0 THEN task2time END AS task2time,
    CASE WHEN task3occ = 0 THEN task3time END AS task3time,
    CASE WHEN task4occ = 0 THEN task4time END AS task4time,
    CASE WHEN task5occ = 0 THEN task5time END AS task5time
FROM yourTable;

如果您想使用此信息填充 test1表,则可以使用INSERT INTO ... SELECT,其中SELECT只是上面的查询。