select 来自 postgresql 中 json 文件结果的字符串
select from string from outcome of json file in postgresql
在 postgre sql 中,我的 table 具有以下 json 格式的属性列
{"color": true,"view": [184],"school":
[805,812,855,856,857]}
我想写一个专栏,如果学校包含 805,812,855 那么 1 否则 0。下面我试过但它不起作用。
case when json_extract_path_text(attributes, 'school') in
[805,812,855] then 1 else 0 end as school
我该如何解决这个问题?
谢谢。
您可以使用横向交叉连接为每一行创建一个数组,并查看它是否包含 [805,812,855] 中的值。在这里,我假设您想确保它包含所有值,而不是任何值。
with data as (select * from (values
('{"color": true,"view": [184],"school":[805,812,855,856,857]}'::jsonb),
('{"color": true,"view": [184],"school":[805,812]}'::jsonb)
) as v(data))
SELECT school_arr @> '{805,812,855}'
FROM data
CROSS JOIN LATERAL (SELECT ARRAY(SELECT jsonb_array_elements_text(data -> 'school'))) d(school_arr)
;
?column?
----------
t
f
(2 rows)
其实我得到了答案
case when json_extract_path_text(attributes, 'school')::jsonb@>'805' then 1
when json_extract_path_text(attributes, 'school')::jsonb@>'812' then 1
when json_extract_path_text(attributes, 'school')::jsonb@>'855' then 1
else
0 end as school
在 postgre sql 中,我的 table 具有以下 json 格式的属性列
{"color": true,"view": [184],"school":
[805,812,855,856,857]}
我想写一个专栏,如果学校包含 805,812,855 那么 1 否则 0。下面我试过但它不起作用。
case when json_extract_path_text(attributes, 'school') in
[805,812,855] then 1 else 0 end as school
我该如何解决这个问题? 谢谢。
您可以使用横向交叉连接为每一行创建一个数组,并查看它是否包含 [805,812,855] 中的值。在这里,我假设您想确保它包含所有值,而不是任何值。
with data as (select * from (values
('{"color": true,"view": [184],"school":[805,812,855,856,857]}'::jsonb),
('{"color": true,"view": [184],"school":[805,812]}'::jsonb)
) as v(data))
SELECT school_arr @> '{805,812,855}'
FROM data
CROSS JOIN LATERAL (SELECT ARRAY(SELECT jsonb_array_elements_text(data -> 'school'))) d(school_arr)
;
?column?
----------
t
f
(2 rows)
其实我得到了答案
case when json_extract_path_text(attributes, 'school')::jsonb@>'805' then 1
when json_extract_path_text(attributes, 'school')::jsonb@>'812' then 1
when json_extract_path_text(attributes, 'school')::jsonb@>'855' then 1
else
0 end as school