给定一个文本元素数组,我想计算出现的次数,并用文本键和整数值将它们作为子对象返回。
(PostgreSQL 9.4版)
案例1-无参考集
SELECT ARRAY['3G','2G','2G','3G','3G','3G','3G','4G']
应该转换为
SELECT '{"2G": 2, "3G": 5, "4G": 1}'::jsonb
案例2-使用参考集
给定一组可能的条目
ARRAY['2G','3G','4G']
,返回的json还应该包含计数为零的元素。SELECT ARRAY['3G','2G','2G','3G','3G','3G','3G']
应该转换为
SELECT '{"2G": 2, "3G": 5, "4G": 0}'::jsonb
我通过使用
-- case 1
SELECT json_object( array_agg(r.a)::text[],array_agg(r.num)::text[] )
FROM (
SELECT a, count(a) as num
FROM unnest( ARRAY['3G','2G','2G','3G','3G','3G','3G','4G'] ) a
GROUP BY a ORDER BY a
) r;
--case 2
SELECT json_object( array_agg(r.ref)::text[],array_agg(r.num)::text[] )
FROM (
SELECT ref, count(a) as num
FROM unnest( ARRAY['2G','3G','4G'] ) ref
LEFT JOIN unnest( ARRAY['3G','2G','2G','3G','3G','3G','3G'] ) a ON (ref = a)
GROUP BY ref ORDER BY ref
) r;
但是,结果返回一个文本值,例如:
SELECT '{"2G" : "2", "3G" : "5", "4G" : "0"}'::json -- case 2
感谢您的帮助和反馈!
最佳答案
对于您的情况,可以使用aggregatejson_object_agg()
函数,查询将更加简单:
SELECT json_object_agg(r.ref,r.num) result
FROM (
SELECT
ref,
count(a) AS num
FROM unnest(ARRAY ['2G', '3G', '4G']) ref
LEFT JOIN unnest(ARRAY ['3G', '2G', '2G', '3G', '3G', '3G', '3G']) a ON (ref = a)
GROUP BY ref
ORDER BY ref
) r;
结果是:
result
----------------------------------
{ "2G" : 2, "3G" : 5, "4G" : 0 }
(1 row)