如何在PostgreSQL中使用两个内部联接的GROUP BY

时间:2019-03-20 13:36:46

标签: sql postgresql

我是SQL新手,我有一个基本问题。我有3个表和2个内部联接。 这是我的SQL代码:

select   c.name, case when e.time > NOW() then 'Yes' else  'No' end AS "time" 
from table1 as e 
INNER JOIN table2 as a on e.id = a.id  
INNER JOIN table3 as c on a.id = c.id 
where e.conty= 'SAD'  
GROUP BY  c.name;

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

4 个答案:

答案 0 :(得分:0)

要检索的任何字段都必须包含在该查询的GROUP BY子句中。您应在GROUP BY子句中包含“时间”,或将其从查询中排除。

select   c.name, case when e.time > NOW() then 'Yes' else  'No' end AS "time" 
from table1 as e 
INNER JOIN table2 as a on e.id = a.id  
INNER JOIN table3 as c on a.id = c.id 
where e.name = 'JOHN'  
GROUP BY  c.name, time;

答案 1 :(得分:0)

在GROUP BY子句中使用e.time属性。

select c.name, case when e.time > NOW() then 'Yes' else  'No' end AS "time" 
from table1 as e 
INNER JOIN table2 as a on e.id = a.id  
INNER JOIN table3 as c on a.id = c.id 
where e.name = 'JOHN'  
GROUP BY c.name, e.time;

答案 2 :(得分:0)

我猜您要聚合-以及最长时间:

__proto__

答案 3 :(得分:0)

由于只选择带有group by name的行,因此不需要name = 'JOHN'
如果要选择最大time的行,请执行以下操作:

select   
  'JOHN' name, 
  case when max(e.time) > NOW() then 'Yes' else  'No' end AS "time" 
from table1 as e 
INNER JOIN table2 as a on e.id = a.id  
INNER JOIN table3 as c on a.id = c.id 
where e.name = 'JOHN'