我有一个带有 JSONB 列的表,其中包含如下数据:
create table car_stats (
id int primary key,
city varchar,
date timestamp,
info varchar
stats jsonb
)
统计示例:
[
{
"brand": "AUDI",
"status": "NEW"
},
{
"brand": "BMW",
"status": "PRODUCTION"
},
{
"brand": "BMW",
"status": "NEW"
},
{
"brand": "BMW",
"status": "NEW"
},
{
"brand": "BMW",
"status": "DELIVERED"
}
]
我想计算按城市和月份分组的汽车品牌的新/生产/交付百分比
CITY MONTH BRAND NEW PRODUCTION DELIVERED
LONDON 3 AUDI 100% 0 0
PARIS 2 BMW 50% 25% 25%
我尝试了以下方法,但我不知道如何计算 JSON 中的元素(例如,所有 BMW 都处于 NEW 状态)
with cte as (
select stats ->> 'brand',
stats ->> 'status',
city,
date
from car_stats
group by city
),
grouped as (
select cte.brand,
cte.country,
cte.date,
ARRAY_TO_JSON(ARRAY_AGG(base)) as statistics
from cte
group by cte.brand, cte.city, cte.date
),
stats as (
count % statistics somehow here.. ?
)
)