第一步用where筛选符合日期、订单状态和课程的条件,并且用窗口函数创造购买此处的查询列,即
(select *,
count(user_id)over(partition by user_id) as num
from
order_info
where
date>2025-10-15
and status='completed'
and product_name in ('C++','Python','Java')) as a
第二步用case when对client表中团购和非团购的name列进行约束,并用left join 将第一步生成的子查询a表和client表进行连接,最后用where对购买次数大于2的列进行筛选,根据id进行排序,即
select a.id,a.is_group_buy,
case when a.is_group_buy='no' then client.name else null end as client_name
from
(select *,
count(user_id)over(partition by user_id) as num
from
order_info
where
date>2025-10-15
and status='completed'
and product_name in ('C++','Python','Java')) as a
left join
client on client.id=a.client_id
where a.num>=2
order by a.id
请注意,LEFT JOIN 意味着即使 client 表中没有匹配的 client_id,order_info 表中的记录仍然会被返回,但 client.name 将为 NULL(除非 is_group_buy 为 'no')