在json_build_object和group by中的PostgreSQL case语句

时间:2016-09-29 01:46:36

标签: json postgresql

我想在另一个variable_c是指定值的情况下,在json对象中插入一个variable_d。我还需要在GROUP BY语句中包含variable_d,但只有当variable_c是指定值时才需要。

是否可以在json_build_object和group by语句中执行CASE语句?如果是这样,我就无法正确理解语法。

理想情况下,我想要类似的东西:

SELECT json_agg(subquery.*) AS features
FROM
(SELECT json_build_object('variable_a', value_a) 
          AS OBJECT,
        json_build_object('variable_b', value_b, 
          CASE WHEN variable_c = 'yes' THEN 'variable_d', variable_d END) 
          AS properties
 FROM some_table
 GROUP BY variable_a,
          CASE WHEN variable_c = 'yes' THEN variable_d END) subquery

所需的输出是:

[{"object":{"variable_a" : "value"}, "properties":{"variable_b" : "value_b"}}, 
 {"object":{"variable_a" : "value"}, "properties":{"variable_b" : "value_b"}}, 
 {"object":{"variable_a" : "value"}, "properties":{"variable_b" : "value_b"}}, 
 {"object":{"variable_a" : "value"}, "properties":{"variable_b" : "value_b", "variable_d" : "value_d"}}, 
 {"object":{"variable_a" : "value"}, "properties":{"variable_b" : "value_b", "variable_d" : "value_d"}}]

0 个答案:

没有答案