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

如何在SQL中按多平台分类分组统计,生成韦恩图所需数据?

解决方案:生成韦恩图所需的平台组合统计

要实现用户平台使用组合的统计,核心是先聚合每个用户的所有平台,再按组合分组计数,具体步骤和SQL如下:

核心思路

  1. 去重冗余记录:同一个用户多次使用同一平台时,只保留一条有效记录,避免重复统计。
  2. 统一组合格式:对每个用户的平台按固定顺序(如Android → iOS → Web)拼接成字符串,确保相同平台组合的格式一致。
  3. 全组合覆盖:预先定义所有7种可能的平台组合,确保最终结果包含所有韦恩图需要的分组,即使某组合没有用户也显示0。

通用SQL实现(以PostgreSQL为例)

-- 预定义所有需要的平台组合
WITH all_platforms AS (
    SELECT unnest(array[
        'Android', 
        'iOS', 
        'Web', 
        'Android, iOS', 
        'Android, Web', 
        'iOS, Web', 
        'Android, iOS, Web'
    ]) AS platform
),
-- 去重同一用户的同一平台记录
user_platforms AS (
    SELECT DISTINCT user_id, platform
    FROM your_table_name  -- 替换为你的表名
),
-- 生成每个用户的平台组合(按固定顺序拼接)
user_combinations AS (
    SELECT 
        user_id,
        string_agg(platform, ', ' ORDER BY platform) AS platform_combination
    FROM user_platforms
    GROUP BY user_id
),
-- 统计各组合的用户数量
combination_counts AS (
    SELECT 
        platform_combination AS platform,
        COUNT(*) AS total
    FROM user_combinations
    GROUP BY platform_combination
)
-- 关联全组合列表,确保无数据的组合显示0
SELECT 
    ap.platform,
    COALESCE(cc.total, 0) AS total
FROM all_platforms ap
LEFT JOIN combination_counts cc ON ap.platform = cc.platform
ORDER BY 
    CASE ap.platform
        WHEN 'Android' THEN 1
        WHEN 'iOS' THEN 2
        WHEN 'Web' THEN 3
        WHEN 'Android, iOS' THEN 4
        WHEN 'Android, Web' THEN 5
        WHEN 'iOS, Web' THEN 6
        WHEN 'Android, iOS, Web' THEN 7
    END;

MySQL版本适配

如果使用MySQL,只需将user_combinations中的string_agg替换为GROUP_CONCAT:

user_combinations AS (
    SELECT 
        user_id,
        GROUP_CONCAT(platform ORDER BY platform SEPARATOR ', ') AS platform_combination
    FROM user_platforms
    GROUP BY user_id
)

结果说明

执行上述SQL后,会输出你需要的7种平台组合及对应的用户数量,完全匹配韦恩图的数据需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 22:57:35