Postgres 9.6声明时的合并和案例

时间:2019-06-11 16:04:54

标签: sql coalesce case-when postgres-9.6

我正在尝试回填一些数据。该表中的列A可能来自倍数表,我可以对其使用合并功能。如果合并返回null,那么我需要转到另一个表,并根据该表中的值向该列插入一个硬编码值。

Backfill Table - T1
Backfill Column - Column A

Coalesce Tables - TC2, TC3, TC4, TC5,TC6
Coalesce Columns - TC2.C2, TC3.C3, TC4.C4, TC5.C5,TC6.C6

Another Table - AT1
Another Column - CAT1

If CAT1 = 21, then Column A should be 100
If CAT1 = 22, then Column A should be 200
If CAT1 = 23, then Column A should be 300
If CAT1 = 24, then Column A should be 400

假设有多个要回填的列,此处未显示。

INSERT INTO TABLE T1 (COLUMN A)
SELECT
coalesce (TC2.C2, TC3.C3, TC4.C4, TC5.C5,TC6.C6),
',
',
'
FROM A JOIN TC2 blah blah;

我只是不确定如何为AT1表包括条件或案例语句。

编辑:我正在询问合并声明中的案例声明。

1 个答案:

答案 0 :(得分:1)

INSERT INTO TABLE T1 (COLUMN A)
    CASE 
        WHEN (SELECT coalesce (TC2.C2, TC3.C3, TC4.C4, TC5.C5,TC6.C6)) IS NOT NULL
        THEN  (SELECT coalesce (TC2.C2, TC3.C3, TC4.C4, TC5.C5,TC6.C6))
        WHEN AT1.CAT1 = '21' THEN '100'
        WHEN AT1.CAT1 = '22' THEN '200'
        WHEN AT1.CAT1 = '23' THEN '300'
        WHEN AT1.CAT1 = '24' THEN '400'
    END AS NEW_COLUMN_VALUE