我正在尝试编写包含嵌套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
别名。它仍然会给我带来同样的错误。
答案 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)添加别名