You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何合并两个SQL表:获取各国总用户与非活跃用户数

解决方案:生成包含所有国家的总用户数与非活跃用户数统计表

基于你已有的两个CTE(t1和t2),只需要通过左连接关联两个结果集,并处理空值即可得到目标表:

完整SQL代码

with t1 as
(
Select country, count(users.id) AS 'total_users'
from users
group by country
),

t2 as 
(
Select country, count(users.id) AS 'inactive_users' 
From users left join orders on users.id = orders.user_id 
Where orders.created_at is null
Group by Country
)
select 
    t1.country,
    t1.total_users,
    COALESCE(t2.inactive_users, 0) as inactive_users
from t1
left join t2 on t1.country = t2.country
order by t1.country;

关键逻辑说明

  1. 左连接保留所有国家:使用t1 left join t2,确保t1中所有国家都能出现在结果中,即使该国家没有非活跃用户。
  2. 空值转0处理:COALESCE(t2.inactive_users, 0)函数会将t2中不存在对应国家时的NULL值替换为0,满足"无则显示0"的需求。
  3. 可选排序:最后添加order by t1.country可以让结果按国家名称排序,提升可读性。

优化t2的可选写法

原t2的逻辑是正确的,但可以用NOT EXISTS简化写法,通常性能更优:

t2 as 
(
Select country, count(users.id) AS 'inactive_users' 
From users
Where NOT EXISTS (
    SELECT 1 FROM orders WHERE orders.user_id = users.id
)
Group by Country
)

这个写法直接筛选出没有任何订单的用户(即非活跃用户),逻辑更直观,避免了不必要的表连接操作。

内容的提问来源于stack exchange,提问作者ZeusofCode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 02:14:58