必须出现在GROUP BY子句中或用于聚合函数(PostgreSQL)

时间:2014-11-27 07:19:22

标签: mysql postgresql

我有这样的查询:

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

但它显示如下错误:

  

必须出现在GROUP BY子句中或用于聚合函数

它适用于MySQL,但是当我在PostgreSQL中尝试它时它没有用。我想每月显示这样的数据:

enter image description here

但如果我使用此查询:

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

它会显示如下数据:

enter image description here

2 个答案:

答案 0 :(得分:4)

如果通过"工作"你的意思是它随意为每个组选择一个可能的schedate值,你是正确的。但是,postgresql和大多数其他SQL产品都希望您明确指出应该选择什么值

如果每个组中的所有值都相同,则将其放在GROUP BY子句或任意聚合(例如MAX(s.schedate))中都应该有效。如果值不同,请告知服务器应选择哪一个 - MINMAX通常是合适的。

答案 1 :(得分:1)

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 

应该有效