在Postgres中计数JSONB阵列
我有一个Postgres数据库,其中一些列数据存储如下:
Guest_composition | Charging_age |
---|---|
[{“ A”:1,“ B”:1,“ C”:1,“ Children_ages”:[10,5,2,0.1]} ] | 3 |
[{“ a”:1,“ b”:1,“ c”:1,“ children_ages”:[2.5,1,4]}] | 3 |
我想浏览Children_ages阵列并返回计数超过3岁的孩子。我很难使用阵列数据,因为它是JSONB而不是int数组的返回。
第一行应该返回2,因为有2个孩子以上3岁。第二行应该返回1个,因为有1个孩子以上3岁。
我尝试了以下内容,但它没有起作用:
with with with with reservation AS (SELECT jsonb_array_elements(reservations.guest_composition)->'children_ages' as children_ages, charging_age FROM reservations
SELECT (CASE WHEN (reservations.charging_age IS NOT NULL AND reservation.children_ages IS NOT NULL) THEN SUM (何时(repervation.children_ages):: int []> =(revervations.charging_age):: int then 1 else 1 else 1 else 0 ense 0 end end end)as children_to_charge
I have a postgres database where some column data are stored as follow:
guest_composition | charging_age |
---|---|
[{"a": 1, "b": 1, "c": 1, "children_ages": [10, 5, 2, 0.1]}] | 3 |
[{"a": 1, "b": 1, "c": 1, "children_ages": [2.5, 1, 4]}] | 3 |
i want to go over the children_ages array and to return the count of children that are above the age of 3. I am having a hard time to use the array data because it is returns as jsonb and not int array.
the first row should return 2 because there are 2 children above the age of 3. The second row should return 1 because there is 1 child above the age of 3.
I have tried the following but it didn't work:
WITH reservation AS (SELECT jsonb_array_elements(reservations.guest_composition)->'children_ages' as children_ages, charging_age FROM reservations
SELECT (CASE WHEN (reservations.charging_age IS NOT NULL AND reservation.children_ages IS NOT NULL) THEN SUM( CASE WHEN (reservation.children_ages)::int[] >=(reservations.charging_age)::int THEN 1 ELSE 0 END) ELSE 0 END) as children_to_charge
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用SQL JSON路径函数提取所有儿童年龄的数组:
该数组的长度是您要查找的计数:
如果
charging_age_age
是一列,我还不清楚该 数组每一行。如果是这样,您可以将参数传递给JSON路径函数:You can extract an array of all child ages using a SQL JSON path function:
The length of that array is then the count you are looking for:
It's unclear to me if
charging_age
is a column and could change in every row. If that is the case, you can pass a parameter to the JSON path function: