postgres将json数组转换为列

时间:2018-03-22 09:35:22

标签: json postgresql jsonb postgresql-9.6

我在postgres 9.6工作,仍然让我的头围绕json

我有一个带有json对象的列,该对象是一个数字数组,表示重现频率和一周中的几天。

CREATE OR REPLACE VIEW v_events_7 AS
SELECT company_events.id, 
       companies.city, 
       company_events.start_date, 
       company_events.start_time,
       company_event_associated_companies.company_id,
       (CASE WHEN companies.mainSubcategory = '217'
           THEN companies.name 
           WHEN companies.mainSubcategory = '216'
           THEN companies.name
           ELSE (SELECT columnName FROM tableName WHERE 
         companies.mainSubcategory = 'YourData'
 /*This is where I need the name as described above*/ 
   END END) Band
   FROM `company_events`

我想将这些扩展到以下列中:

{"every":"1","weekdays":["1"]}
{"every":"1","weekdays":["1","3"]}
{"every":"1","weekdays":["1","2","3","4","5"]}

ROW1 -[1]          : MON  
ROW2 -[1,3]        : MON , WED  
ROW3 -[1,2,3,4,5]  : MON , TUE , WED , THU , FRI  

我可以使用|ROW- |MON | TUE| WED|THU|FRI| ------------------------------ |ROW1 |Y |N |N |N |N | |ROW2 |Y |N |Y |N |N | |ROW3 |Y |Y |Y |Y |Y | 获取元素,但接着是什么?

我想使用'包含'用于构建每列的表达式

jsonb_array_elements(pattern)pattern @> '{1}'等,但我无法构建一个会产生影响的对象

2 个答案:

答案 0 :(得分:2)

示例数据:

create table my_table(id serial primary key, pattern jsonb);
insert into my_table (pattern) values
('{"weekdays": [1]}'),
('{"weekdays": [1, 3]}'),
('{"weekdays": [1, 2, 3, 4, 5]}');

您可以使用运算符@>这样:

select 
    id,
    pattern->'weekdays' @> '[1]' as mon,
    pattern->'weekdays' @> '[2]' as tue,
    pattern->'weekdays' @> '[3]' as wed,
    pattern->'weekdays' @> '[4]' as thu,
    pattern->'weekdays' @> '[5]' as fri
from my_table

 id | mon | tue | wed | thu | fri 
----+-----+-----+-----+-----+-----
  1 | t   | f   | f   | f   | f
  2 | t   | f   | t   | f   | f
  3 | t   | t   | t   | t   | t
(3 rows)    

答案 1 :(得分:0)

似乎我正走在正确的轨道上,包含'但我对阵中的内容感到困惑。我应该一直在寻找一个不是数字的字符串

, bookings.pattern->'weekdays' @> '"1"'::jsonb

感谢Pitto提示将外部json放入显而易见的问题中