PostgreSQL:无法从嵌套选择

时间:2016-07-21 17:53:50

标签: sql postgresql

我正在尝试编写包含嵌套SELECT的查询。但是,当我尝试运行我的代码时,Postgres会抛出此错误:ERROR: column bo_wins.opportunity_id does not exist。这是查询:

SELECT b.owner_id AS "Owner ID",
       COUNT(DISTINCT bo.id) AS "Number of Opportunities",
       COALESCE(bo_wins.count, 0) AS "Number of Wins"
FROM bookings b
INNER JOIN booking_opportunities bo ON bo.id = b.opportunity_id
LEFT JOIN (
     SELECT b.owner_id AS "Owner ID", COUNT(DISTINCT bo.id) AS "count"
     FROM bookings b 
     INNER JOIN booking_opportunities bo ON bo.id = b.opportunity_id 
     WHERE bo.state IN ('won') AND TO_CHAR(bo.created_at, 'yyyy-mm') = '2016-06' 
     GROUP BY b.owner_id
     ) AS bo_wins ON bo_wins.opportunity_id = b.opportunity_id
WHERE TO_CHAR(bo.created_at, 'yyyy-mm') = '2016-06'
GROUP BY bo_wins.count, b.owner_id;

希望有人能够帮助我。我需要做一个子查询的原因是因为我们的数据库是如何构建的(我知道!效率不高,是吗?)

编辑:我在子查询中将COUNT别名。它仍然会给我带来同样的错误。

2 个答案:

答案 0 :(得分:1)

更新了答案

我认为你想要做的事情更好地代表了这一点:

SELECT
    b.owner_id AS owner_id,
    COUNT(DISTINCT bo.id) AS opportunities,
    COUNT(DISTINCT CASE WHEN bo.state = 'won' THEN bo.id END) AS wins
FROM
    bookings b 
INNER JOIN
    booking_opportunities bo
    ON (bo.id = b.opportunity_id)
WHERE
    TO_CHAR(bo.created_at, 'yyyy-mm') = '2016-06' 
GROUP BY
    b.owner_id;

这为您提供了每个owner_id的机会数和获胜次数。

初步回答

您需要为计算提供别名,并且需要在同一个select语句中包含opportunity_id

COUNT(DISTINCT bo.id) AS "count"

此外,在您的GROUP BY中,您需要将bo.wins.count更改为bo_wins.count

答案 1 :(得分:1)

哟应该为COUNT(DISTINCT bo.id)添加别名