数据函数在子查询中对项目进行分组

时间:2016-02-18 08:20:10

标签: sql postgresql group-by

我正在使用Postgresql来编写一个查询,该查询每天计算diff值的总和并从其他表il_costs获取单价,这是我尝试使用子查询实现的。整个查询下面:

SELECT date(read.readed_at), 
       SUM(read.diff), 
       (SELECT water_unit 
        FROM il_costs 
        WHERE EXTRACT(MONTH FROM created_at) = EXTRACT(MONTH FROM date(read.readed_at)) 
          AND EXTRACT(YEAR FROM created_at) = EXTRACT(YEAR FROM date(read.readed_at))) 
FROM il_communicators_readings read 
GROUP BY date(read.readed_at) 
ORDER BY date(read.readed_at) ASC;

我收到有关未分组列的错误,但我在分组函数中也使用了date(read.readed_at)

ERROR: subquery uses ungrouped column "read.readed_at" from outer query
LINE 1: ...(MONTH FROM created_at) = EXTRACT(MONTH FROM date(read.reade...

2 个答案:

答案 0 :(得分:1)

您可以尝试将查询用作子查询,并在外部查询中执行相关子查询:

SELECT mydate, s_diff,
       (SELECT water_unit 
        FROM il_costs 
        WHERE EXTRACT(MONTH FROM created_at) = EXTRACT(MONTH FROM mydate) 
          AND EXTRACT(YEAR FROM created_at) = EXTRACT(YEAR FROM mydate)) 
FROM (
  SELECT date(read.readed_at) AS mydate, 
         SUM(read.diff) as s_diff
  FROM il_communicators_readings read 
  GROUP BY date(read.readed_at) ) AS t
ORDER BY mydate ASC;

答案 1 :(得分:0)

问题不在于read.readed_at,它是不在group by中的子查询。并且我认为使用这样的子查询是个好主意。

试试这个:

SELECT date(read.readed_at), 
   SUM(read.diff), 
   costs.water_unit
FROM il_communicators_readings read 
Left Join il_costs costs
ON EXTRACT(MONTH FROM costs.created_at) = EXTRACT(MONTH FROM date(read.readed_at)) 
AND EXTRACT(YEAR FROM costs.created_at) = EXTRACT(YEAR FROM date(read.readed_at))
GROUP BY date(read.readed_at),costs.water_unit
ORDER BY date(read.readed_at) ASC;