Postgres为什么会出现这个错误

时间:2013-02-12 15:36:57

标签: sql database postgresql

我有以下查询

select wbod.subject, wbi.object, 
       age(dod.object,wbod.object) as ageOfPerson 
from wasbornin as wbi, 
     wasbornondate as wbod, 
     diedondate as dod 
where wbi.subject=wbod.subject 
  and wbod.subject=dod.subject  
  and age(dod.object,wbod.object) = (select max(age(dod1.object,wbod1.object)) 
                                     from wasbornin as wbi1, 
                                     wasbornondate as wbod1, 
                                     diedondate as dod1 
                                     where wbi1.subject = wbod1.subject 
                                     and wbod1.subject=dod1.subject 
                                     group by wbi1.object)   
group by wbi.object 
ORDER BY wbi.subject;

但是它给出了以下错误

column "wbod.subject" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: select wbod.subject, wbi.object

为什么会出现此错误

2 个答案:

答案 0 :(得分:2)

那是因为您正在选择此列。如果给定组(GROUP BY wbi.object)有150个不同的科目,其中一个应该被退回?

我最初误读了查询 - 顺序是使用wbi.subject,但错误是关于wbod.subject。

答案 1 :(得分:1)

如果我正确理解您的查询,您实际上不需要子查询或组:

select subject,
       object,
       ageOfPerson
from (
    select wbod.subject, 
           wbi.object, 
           age(dod.object, wbod.object) as ageOfPerson,
           dense_rank() over (partition by dod.subject order by age(dod.object, wbod.object) desc) as rnk
    from wasbornin as wbi
      join wasbornondate as wbod on wbi.subject=wbod.subject 
      join diedondate as dod on wbod.subject=dod.subject  
) t
where rnk = 1;