postgresql 错误代码子查询使用外部查询中未分组的列

8tntrjer  于 2023-03-29  发布在  PostgreSQL
关注(0)|答案(2)|浏览(302)

谁能帮我一下我的代码有什么问题吗

SELECT agent.agent_name AS agent_name,
       (SELECT COUNT(assigned.id_agent))AS itung,
       (SELECT COUNT(ticket.id_agent) WHERE ticket.id_status = 4) AS itung2
FROM agent
  LEFT JOIN assigned ON agent.id = assigned.id_agent
  LEFT JOIN ticket ON agent.id = ticket.id_agent
GROUP BY agent.id

我得到错误代码子查询使用外部查询中未分组的列“ticket.id_status”
第3行:(SELECT COUNT(ticket.id_agent)WHERE ticket.id_status = 4)AS ...

ulydmbyx

ulydmbyx1#

这是一个有点不清楚我你想达到什么目的,但我认为你正在寻找过滤器。
但是由于agent.agent_name是唯一一个未分组的列,因此必须按 that 进行分组:

SELECT agent.agent_name AS agent_name,
       COUNT(assigned.id_agent) AS itung,
       COUNT(ticket.id_agent) FILTER (WHERE ticket.id_status = 4) AS itung2
FROM agent
  LEFT JOIN assigned ON agent.id = assigned.id_agent
  LEFT JOIN ticket ON agent.id = ticket.id_agent
GROUP BY agent.agent_name;
mv1qrgav

mv1qrgav2#

查看您的查询,您显然在group by子句中缺少了ticket.id_status

查询可以通过聚合函数进一步简化,以计算itung2的值,如下所示:

SELECT agent.agent_name AS agent_name,
    COUNT(assigned.id_agent) AS itung,
    COUNT(ticket.id_agent) AS itung2
FROM agent
LEFT JOIN assigned ON agent.id = assigned.id_agent
LEFT JOIN ticket ON agent.id = ticket.id_agent AND ticket.id_status = 4
GROUP BY agent.id, agent.agent_name;

相关问题