如何将查询的输出用作第二个查询中的 where 参数

How to use an output of a query as a where parameter in a second query

我有此查询要列出 top_10潜在客户细分:

select segment as "Segment", count(*) as "Qty" from table
where id >=1
group by segment
order by 2 desc
limit 10

现在我想使用上面查询中的第一个段(limit 1 desc)在 where 子句中使用以列出来自该特定段的所有角色。假设第一个查询中的 top_1 段是航空。

那我想这样查询:

select role, count(*) from table
where segment = 'aviation'
group by role
order by 2 desc

我该怎么做?

您可以使用分析计数函数获取每个片段的计数,然后使用 first_value 获取顶部片段,然后进行过滤。看代码中的注释:

select role, count(*)
from
(
select segment, role,
       --Get Top segment
       first_value(segment) over(order by segment_cnt desc rows between UNBOUNDED PRECEDING and UNBOUNDED FOLLOWING ) as top_segment
from
    (
     select --calculate segment counts
           segment, role, 
           count(case when id>=1 then 1 else null end) over (partition by segment) as segment_cnt
      from table
    )s
)s
WHERE segment=top_segment --filter only top 1 segment
GROUP BY role
ORDER BY 2 desc