我有以下sql查询:
SELECT
distinct(date(survey_results.created_at)),
ROUND(
COUNT(*) FILTER (WHERE (
scores#>>'{medic,social,total}' in('high', 'medium'))) OVER(order by date(survey_results.created_at)
) * 1.0 /
(CASE (COUNT(*) FILTER (WHERE (scores#>>'{medic,social,total}' in('high','medium','low') or coalesce(raw#>>'{survey, denied}', 'f') = 'true')) OVER(order by date(survey_results.created_at)))
WHEN 0.0 THEN 1.0
ELSE (COUNT(*) FILTER (WHERE (scores#>>'{medic,social,total}' in('high','medium','low') or coalesce(raw#>>'{survey, denied}', 'f') = 'true')) OVER(order by date(survey_results.created_at)))
END)* 100, 2
) AS positive,
ROUND(
COUNT(*) FILTER (WHERE (
scores#>>'{medic,social,total}' in('low'))) OVER(order by date(survey_results.created_at)
) * 1.0 /
(CASE (COUNT(*) FILTER (WHERE (scores#>>'{medic,social,total}' in('high','medium','low') or coalesce(raw#>>'{survey, denied}', 'f') = 'true')) OVER(order by date(survey_results.created_at)))
WHEN 0.0 THEN 1.0
ELSE (COUNT(*) FILTER (WHERE (scores#>>'{medic,social,total}' in('high','medium','low') or coalesce(raw#>>'{survey, denied}', 'f') = 'true')) OVER(order by date(survey_results.created_at)))
END)* 100, 2
) AS negative
FROM survey_results
GROUP BY date, scores, raw
ORDER BY date ASC;
我试图让它变得更干爽和可读。有什么建议吗?
答案 0 :(得分:0)
对于positive
,您可以尝试以下逻辑:
AVG(CASE WHEN scores#>>'{medic,social,total}' in ('high', 'medium')
THEN 100.0
WHEN scores#>>'{medic,social,total}' in ('low')
THEN 0.0
END) OVER (ORDER BY date(survey_results.created_at) as positive
(negative
的类似逻辑。)
我认为这封装了你的逻辑,除了当没有匹配时它返回NULL
而不是0
。如果这是一个问题,您可以使用COALESCE()
。