如果类型正确,则设置属性值

时间:2018-08-21 14:00:02

标签: postgresql

因此,我需要根据类型设置属性的值。为了使形象化,我有这张桌子(让我们把桌子叫做“ forecasts”):

| creation_time | id |    d_type    |    d_amount  |
|---------------|--- |--------------|--------------|
|    1534842000 |  1 |           2  |          1.3 |
|    1534842000 |  2 |           3  |          0.3 |

d_type表示它是哪种类型,例如,假设:

1 = nothing
2 = rain
3 = snow

如何获得一个看起来像这样的表:

| creation_time | id |    rain      |    snow      |
|---------------|--- |--------------|--------------|
|    1534842000 |  1 |          1.3 |            0 |
|    1534842000 |  2 |            0 |          0.3 |

也就是说,如果属性对应于右边的d_amount,则属性的值应为d_type

我尝试过这样的事情:

SELECT
        creation_time,
        id,
        "rain", CASE d_type WHEN 2 THEN d_amount END,
        "snow", CASE d_type WHEN 3 THEN d_amount END,
FROM forecasts;

但是它返回一个我不想要的大小写列。我是PostgreSQL的新手,非常抱歉。感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

尝试

SELECT
    creation_time,
    id,
    CASE d_type WHEN 2 THEN d_amount END as "rain",
    CASE d_type WHEN 3 THEN d_amount END as "snow",
  FROM forecasts;