我的数据库中有以下表格:
CREATE TABLE survey_results (
id integer NOT NULL,
scores jsonb DEFAULT '{}'::jsonb,
created_at timestamp without time zone,
updated_at timestamp without time zone
);
我使用以下查询从此表中获取数据:
SELECT
date(survey_results.created_at),
json_build_object(
'high', COUNT(*) FILTER (WHERE (scores#>>'{medic,categories,food_insecurity}' in('high'))),
'medium', COUNT(*) FILTER (WHERE (scores#>>'{medic,categories,food_insecurity}' in('medium'))),
'low', COUNT(*) FILTER (WHERE (scores#>>'{medic,categories,food_insecurity}' in('low')))
) as food_insecurity,
json_build_object(
'high', COUNT(*) FILTER (WHERE (scores#>>'{medic,categories,motivation}' in('high'))),
'medium', COUNT(*) FILTER (WHERE (scores#>>'{medic,categories,motivation}' in('medium'))),
'low', COUNT(*) FILTER (WHERE (scores#>>'{medic,categories,motivation}' in('low')))
) as motivation
FROM survey_results
GROUP BY date(survey_results.created_at);
我想重构此查询以返回记录百分比而不是计数。我怎样才能做到这一点?这是你可以试验的sql小提琴。
答案 0 :(得分:0)
我认为你可以做到:
'high', AVG(CASE WHEN scores#>>'{medic,categories,food_insecurity}' in (' high') THEN 1.0 ELSE 0 END),
或者更加神秘:
'high', AVG( (scores#>>'{medic,categories,food_insecurity}' in (' high'))::int),
答案 1 :(得分:0)