我想说明表格opportunities
中的实体是否加价。一个公司可以拥有多个机会(1:N),当机会与公司建立联系并且过去的其他一些机会已经成功完成业务(因此status
是7)与同一家公司合作时,追加销售是正确的。换句话说,状态7的第一次机会不是追加销售,所有其他同一公司的机会都是追加销售,无论其状态如何。
所以这就是我尝试过的
SELECT opportunities.id ,true as upsell FROM opportunities, (
SELECT companies.id as company_id, opportunities.id as opportunity_id
FROM opportunities
JOIN companies ON companies.id = opportunities.company_id
WHERE opportunities.status = 7
GROUP BY companies.id, opportunities.id
HAVING min(opportunities.created_at) = opportunities.created_at)
AS subs WHERE subs.opportunity_id = opportunities.id
这里的想法是在子选择中选择所有首先成功完成的机会(基于created_at
列),然后将其从具有相同公司的所有商机中删除。然而,即使subselect无法正常工作,它也会返回由status = 7
过滤的所有机会,因此我可能会误解group by子句。
-
答案 0 :(得分:1)
如果我理解正确,您希望在以下情况下将opportunities
标记为true:
如果是这样,我认为这更简单:
select o.*,
(row_number() over (partition by o.company_id, o.status
order by created_at
) > 1 or
status <> 7
) as upsell_flag
from opportunities o;