简体   繁体   中英

Must appear in the GROUP BY clause or be used in an aggregate function (PostgreSQL)

I have query like this :

select u.fullname ,s.schedate,
sum(case when s.isvisiting =1 then s.isvisiting else 0 end) as visit ,
count(s.custid) as cust, 
sum(case when s.isclosing = 1 then s.isclosing else 0 end)as orders 
from vmstrschedule s JOIN vmsmsuser u ON u.usercode = s.salesmanid 
where u.branchid = 'BLL' group by u.fullname

but it shows error like this :

must appear in the GROUP BY clause or be used in an aggregate function

it works in MySQL , but when I tried it in PostgreSQL it didn't work . I want to display data like this , per month :

在此处输入图片说明

but if I used this query :

select u.fullname,s.schedate,
sum(case when s.isvisiting =1 then s.isvisiting else 0 end) as visit ,
count(s.custid) as cust, 
sum(case when s.isclosing = 1 then s.isclosing else 0 end)as orders 
from vmstrschedule s JOIN vmsmsuser u ON u.usercode = s.salesmanid 
where u.branchid = 'BLL' group by u.fullname,s.schedate
order by u.fullname

it will shows data like this :

在此处输入图片说明

If by "works" you mean it arbitrarily selects one of the possible schedate values for each group, you're correct. However, postgresql and most other SQL products want you to be explicit about what value they should select

If all the values are the same within each group, putting it in either the GROUP BY clause or an arbitrary aggregate (eg MAX(s.schedate) ) should work. If the values are different, please tell the server which one it should select - the MIN , or MAX would usually be appropriate.

select u.fullname ,s.schedate,
sum(case when s.isvisiting =1 then s.isvisiting else 0 end) as visit ,
count(s.custid) as cust, 
sum(case when s.isclosing = 1 then s.isclosing else 0 end)as orders 
from vmstrschedule s JOIN vmsmsuser u ON u.usercode = s.salesmanid 
where u.branchid = 'BLL' group by u.fullname, s.schedate 

should work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM