选择和连接错误必须出现在GROUP BY子句中或用于聚合函数

时间:2014-11-04 20:02:52

标签: sql postgresql postgresql-9.1

我正在尝试这样做:

SELECT *,
case when SUM(fld_allocated_time) / 24 < fld_allocated_days 
then 'OK'
else 'NOK' 
end as Alocated
from
(
SELECT tbl_project.fld_id, tbl_project.fld_allocated_days, 
tbl_project_timesheet.fld_allocated_time 
FROM "SD_PRJ".tbl_project
INNER JOIN "SD_PRJ".tbl_project_timesheet
ON tbl_project.fld_id=tbl_project_timesheet.fld_id
) AS Alias

我收到此错误:

ERROR: column "total.fld_id" must appear in the GROUP BY clause or be used in an aggregate function
SQL state: 42803
Character: 8

tbl =表
fld =列
SD_PRJ =架构名称

2 个答案:

答案 0 :(得分:1)

将选择列表中的其他列添加到您的GROUP BY

) AS Alias
GROUP BY fld_id, fld_allocated_days, fld_allocated_time

答案 1 :(得分:1)

如果您想为查询的所有行计算一个总和,并将其与每行中的fld_allocated_days进行比较,那么您可以尝试这样做:

with Alias as (
SELECT * from (
    SELECT tbl_project.fld_id, tbl_project.fld_allocated_days, 
           tbl_project_timesheet.fld_allocated_time 
    FROM "SD_PRJ".tbl_project
         INNER JOIN "SD_PRJ".tbl_project_timesheet
         ON tbl_project.fld_id=tbl_project_timesheet.fld_id
)
select a.*, 
       case when b.sm < fld_allocated_days then 'OK' else 'NOK' end as Alocated
from Alias a cross join
    (select SUM(fld_allocated_time) / 24 sm from Alias) b;

但是,我想你需要这样的东西:

SELECT tbl_project.fld_id,
       case when SUM(tbl_project_timesheet.fld_allocated_time) / 24 
                 < fld_allocated_days 
            then 'OK' 
            else 'NOK' 
       end as Alocated
FROM "SD_PRJ".tbl_project
     INNER JOIN "SD_PRJ".tbl_project_timesheet
     ON tbl_project.fld_id=tbl_project_timesheet.fld_id
GROUP BY tbl_project.fld_id, tbl_project.fld_allocated_days;