PostgreSQL - 无法识别json类型的相等运算符

时间:2018-01-24 10:40:45

标签: sql json postgresql

我有以下查询:

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

这是db小提琴,显示问题:

https://www.db-fiddle.com/f/vUBjUyKDUNLWzySHKCKcXA/1

我该如何解决?

2 个答案:

答案 0 :(得分:4)

  

问题在于使用distinct(date(survey_results.created_at))

没有。问题在于使用DISTINCT - 这是不是一个函数。它始终适用to all columns of the resultdistinct(a), bdistinct a, (b)distinct a, b相同。因此,不同的尝试比较第二列的相同值,这些值是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; 

distinct on ()order by结合,为ON ()部分中指定的列的后续相同值选取第一行。在这种情况下,它将返回最早的日期。如果您想要“最新”行,请将排序顺序更改为desc

https://www.db-fiddle.com/f/vUBjUyKDUNLWzySHKCKcXA/1

答案 1 :(得分:0)

使用jsonb_build_object。请注意b之后的json二进制文件。