[英]Filter json values regardless of keys in PostgreSQL
I have a table called diary
which includes columns listed below: 我有一个称为
diary
的表,其中包含以下列出的列:
| id | user_id | custom_foods |
|----|---------|--------------------|
| 1 | 1 | {"56": 2, "42": 0} |
| 2 | 1 | {"19861": 1} |
| 3 | 2 | {} |
| 4 | 3 | {"331": 0} |
I would like to count how many diaries having custom_foods
value(s) larger than 0 each user have. 我想计算每个用户有多少
custom_foods
值大于0的日记。 I don't care about the keys, since the keys can be any number in string. 我不在乎键,因为键可以是字符串中的任何数字。
The desired output is: 所需的输出是:
| user_id | count |
|---------|---------|
| 1 | 2 |
| 2 | 0 |
| 3 | 0 |
I started with: 我开始于:
select *
from diary as d
join json_each_text(d.custom_foods) as e
on d.custom_foods != '{}'
where e.value > 0
I don't even know whether the syntax is correct. 我什至不知道语法是否正确。 Now I am getting the error:
现在我得到了错误:
ERROR: function json_each_text(text) does not exist
错误:函数json_each_text(text)不存在
LINE 3: join json_each_text(d.custom_foods) as e第3行:以e身份加入json_each_text(d.custom_foods)
HINT: No function matches the given name and argument types.
提示:没有函数匹配给定的名称和参数类型。 You might need to add explicit type casts.
您可能需要添加显式类型转换。
My using version is: psql (10.5 (Ubuntu 10.5-1.pgdg14.04+1), server 9.4.19). 我使用的版本是:psql(10.5(Ubuntu 10.5-1.pgdg14.04 + 1),服务器9.4.19)。 According to PostgreSQL 9.4.19 Documentation , that function should exist.
根据PostgreSQL 9.4.19 Documentation ,该功能应该存在。 I am so confused that I don't know how to proceed now.
我很困惑,我现在不知道该如何进行。
Threads that I referred to: 我提到的线程:
Your custom_foods
column is defined as text, so you should cast it to json before applying json_each_text
. 您的
custom_foods
列定义为text,因此您应在应用json_each_text
之前将其json_each_text
为json。 As json_each_text
by default does not consider empty jsons, you may get the count as 0 for empty jsons from a separate CTE and do a UNION ALL
由于默认情况下
json_each_text
不考虑空json,因此您可以从单独的CTE中将空json的计数计为0,然后执行UNION ALL
WITH empty AS
( SELECT DISTINCT user_id,
0 AS COUNT
FROM diary
WHERE custom_foods = '{}' )
SELECT user_id,
count(CASE
WHEN VALUE::int > 0 THEN 1
END)
FROM diary d,
json_each_text(d.custom_foods::JSON)
GROUP BY user_id
UNION ALL
SELECT *
FROM empty
ORDER BY user_id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.