重构PostgreSQL查询以返回百分比而不是计数

时间:2018-01-22 18:06:50

标签: sql postgresql

我的数据库中有以下表格:

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小提琴。

http://sqlfiddle.com/#!17/5a86e/1

2 个答案:

答案 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)

How can I retrieve the hyperlink from a data cell in google apps script?

{{1}}

您可以根据需要调整舍入和过滤器。