如何修复列必须出现在sql select中的group by子句错误中

时间:2018-02-17 15:15:02

标签: sql postgresql

是postgres,sql脚本

create temp table dok ( dokumnr serial primary key, kuupaev date not null ) on commit drop;
create temp table omdok ( dokumnr serial primary key, kuupaev date not null ) on commit drop;
create temp table omrid ( dokumnr int references omdok, tasudjrk int references dok ) on commit drop;

      select dok.dokumnr ,
    ( 
    SELECT MAX(kuupaev)
     from 
    (select MAX(omdok.kuupaev)
           from omdok
            join omrid using (dokumnr)
           where omrid.tasudjrk=dok.dokumnr
    limit 1
    ) x
    ) as maxtasu
        from DOK 

导致错误

ERROR:  column "dok.dokumnr" must appear in the GROUP BY clause or be used in an aggregate function
LINE 7:    select dok.dokumnr ,
                  ^

********** Error **********

ERROR: column "dok.dokumnr" must appear in the GROUP BY clause or be used in an aggregate function
SQL state: 42803
Character: 330

如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

您使用MAX女巫是一个集合函数,因此需要添加group by

你可以试试这个。

select dok.dokumnr ,
( 
    SELECT MAX(kuupaev)
    from 
    (
        select MAX(omdok.kuupaev)
        from omdok
        join omrid using (dokumnr)
        where omrid.tasudjrk=dok.dokumnr
        limit 1
    ) x
) as maxtasu
from DOK 
group by dok.dokumnr