我有一个资产数量表如下
id | asset_type | quantity | site_id | asset_ids_json
1 'Container' 3 1 [{"id":1,"make":"am1","model":"amo1"},{"id":2,"make":"am1","model":"amo2"},{"id":3,"make":"am3","model":"amo3"}]
2 'Cage' 3 1 [{"id":4,"make":"bm1","model":"bmo1"},{"id":5,"make":"bm2","model":"bmo2"},{"id":6,"make":"bm2","model":"cmo3"}]
3 'Crate' 3 1 [{"id":7,"make":"cm1","model":"cmo1"},{"id":8,"make":"cm1","model":"cmo1"},{"id":9,"make":"cm1","model":"cmo2"}]
我想在 Postgres 中编写一个 SQL 查询,它将为我提供给定品牌或型号的每种资产类型的数量计数。
例如,如果我想获取 make='am1' 的每种资产类型的数量,
site_id | Container_qty | Cage_qty | Crate_qty
1 2 0 0
例如,如果我想获取 make='cm1' 的每种资产类型的数量,结果集将如下所示
site_id | Container_qty | Cage_qty | Crate_qty
1 0 0 3
我已经编写了下面的查询,以将“asset_type”行中的值转换为列,但无法弄清楚如何根据“asset_ids_json”字段中的属性过滤和聚合计数。可以安全地假设asset_ids_json 中的json 数组的长度将始终与“数量”列中的值相同。
select
aq.site_id,
sum(case when aq.asset_type = 'Container' then aq.quantity end) container_qty,
sum(case when aq.asset_type = 'Cage' then aq.quantity end) cage_qty ,
sum(case when aq.asset_type = 'Crate' then aq.quantity end) crate_qty,
from asset_quantities aq
group by aq.site_id;
我的问题的关键是如何根据 json 列“asset_ids_json”中的属性过滤和聚合结果。我正在使用 Postgres 9.4。