我有以下疑问:
SELECT
distinct(date(survey_results.created_at)),
json_build_object(
'high',
ROUND(
COUNT(*) FILTER (WHERE ( scores#>>'{medic,categories,motivation}' in('high', 'medium'))) OVER(order by date(survey_results.created_at) ) * 1.0 /
(
CASE (COUNT(*) FILTER (WHERE (scores#>>'{medic,categories,motivation}' in('high','medium','low'))) OVER(order by date(survey_results.created_at)))
WHEN 0.0 THEN 1.0
ELSE (COUNT(*) FILTER (WHERE (scores#>>'{medic,categories,motivation}' in('high','medium','low'))) OVER(order by date(survey_results.created_at)))
END)* 100, 2 ) ) AS childcare FROM survey_results GROUP BY date, scores ORDER BY date asc;
问题出在使用distinct(date(survey_results.created_at))
上。这样,查询就会返回错误:
could not identify an equality operator for type json
下面是显示问题数据库小提琴:
https://www.db-fiddle.com/f/vUBjUyKDUNLWzySHKCKcXA/1
我怎么才能修复它呢?
发布于 2018-01-24 18:48:39
使用jsonb_build_object
。请注意json
之后的二进制文件的b
。
发布于 2018-01-24 18:52:41
问题出在使用
distinct(date(survey_results.created_at))
上
不是的。问题在于使用DISTINCT
--即is 而不是a function。它始终应用to all columns of the result。distinct(a), b
与distinct a, (b)
或distinct a, b
相同。正因为如此,distinct会尝试比较第二列的相同值,该列的类型为json,不能与=
进行比较
如果你只想要最新的值,你可以用Postgres的distinct on ()
操作符来实现:
SELECT distinct on (date(survey_results.created_at))
date(survey_results.created_at) as date,
json_build_object('high',
ROUND(
COUNT(*) FILTER (WHERE ( scores#>>'{medic,categories,motivation}' in('high', 'medium'))) OVER(order by date(survey_results.created_at) ) * 1.0 /
(
CASE (COUNT(*) FILTER (WHERE (scores#>>'{medic,categories,motivation}' in('high','medium','low'))) OVER(order by date(survey_results.created_at)))
WHEN 0.0 THEN 1.0
ELSE (COUNT(*) FILTER (WHERE (scores#>>'{medic,categories,motivation}' in('high','medium','low'))) OVER(order by date(survey_results.created_at)))
END)* 100, 2 ) ) AS childcare
FROM survey_results
GROUP BY date, scores
ORDER BY date asc;
与order by
结合使用的distinct on ()
为ON ()
部件中指定的列的后续相同值选取第一行。在这种情况下,它将返回最早的日期。如果需要“最新”行,请将排序顺序更改为desc
发布于 2022-01-08 04:20:40
迁移到使用JSONB,您就不会有这个问题。
这是几年前Postgres 9.4问世时遵循的标准建议。这是Ruby on Rails社区中的一个帖子,它描述了迁移到JSONB作为解决方案。
https://stackoverflow.com/questions/48420438
复制相似问题