我正在尝试使用以下查询来根据时间获取行。当我得到行时,我想平均列中的值,并返回一行,其平均值为JSON。希望它能用一些代码来理解。这是我开始的PostgreSQL查询:
select row_to_json(row)
from (
SELECT "responses"."index", "responses"."created_at",
ROUND(AVG("responses"."value")) AS value
FROM "responses"
WHERE "responses"."time" = '1416177080'
GROUP BY "responses"."index", "responses"."created_at"
) row
产生如下输出:
{"index":4,"created_at":"2014-11-16 22:31:27","value":5}
{"index":4,"created_at":"2014-11-16 22:31:23","value":-5}
{"index":4,"created_at":"2014-11-16 22:31:24","value":0}
{"index":4,"created_at":"2014-11-16 22:31:25","value":-1}
{"index":4,"created_at":"2014-11-16 22:31:26","value":1}
(5 rows)
当我真正想要的只是一行时,平均值为值。像这样:
{"index_of_affiliation":4,"created_at":"2014-11-16 22:31:27","value":0}
我觉得created_at
可能会让我失望,但我想在JSON中返回一个值。任何关于如何获得我想要的平均值的行的反馈都会有所帮助。
答案 0 :(得分:1)
这些方面的某些内容可能有用。
select row_to_json(row)
from (select "index" index_of_affiliation,
max("created_at") max_created_at,
round(avg("value")) avg_value
from responses
where "time" = '1416177080'
group by "index"
) row ;
从长远来看,你最好使用更具描述性的名字而不是" index"," value"," time"。