#成为 SQL 大师#groupby 中不能有聚合函数

背景

复制代码
select 
    t1.p_date,
    t1.member_id,
    top3_domains,
    CASE WHEN label_code = 'realtime' THEN COLLECT_SET(bayes_first) END as realtime_bys
    from 
    create_top3 t1 
    join consume_profile t2 
    on t1.p_date=t2.p_date 
    and cast(t1.member_id as string)=cast(t2.member_id as string)
    group by 1,2,3,4


报错:
aggregate functions are not allowed in GROUP BY, but found CASE WHEN (t2.`label_code` = 'realtime') THEN collect_set(t2.`bayes_first`) END;

原因&解决方案

你遇到的错误是因为在 GROUP BY 子句中,不能包含聚合函数(如 COLLECT_SET)之外的其他列或表达式。在这种情况下,你可以使用子查询来解决问题。以下是一种修改方法:

复制代码
SELECT 
    t1.p_date,
    t1.member_id,
    top3_domains,
    MAX(CASE WHEN t2.label_code = 'realtime' THEN t2.collect_set_bayes_first END) AS realtime_bys
FROM 
    create_top3 t1 
JOIN 
    (
        SELECT
            p_date,
            member_id,
            label_code,
            COLLECT_SET(bayes_first) AS collect_set_bayes_first
        FROM 
            consume_profile
        WHERE 
            label_code IN ('text_bayes_first_realtime', 'text_bayes_first_short_term', 'text_bayes_first_long_term')
        GROUP BY 
            p_date,
            member_id,
            label_code
    ) t2
ON 
    t1.p_date = t2.p_date 
    AND cast(t1.member_id as string) = cast(t2.member_id as string)
GROUP BY 
    1, 2, 3;

声明:本文章有 AI 辅助

相关推荐
AAA修煤气灶刘哥9 小时前
后端人速藏!数据库PD建模避坑指南
数据库·后端·mysql
RestCloud13 小时前
揭秘 CDC 技术:让数据库同步快人一步
数据库·api
得物技术16 小时前
MySQL单表为何别超2000万行?揭秘B+树与16KB页的生死博弈|得物技术
数据库·后端·mysql
可涵不会debug20 小时前
【IoTDB】时序数据库选型指南:工业大数据场景下的技术突围
数据库·时序数据库
ByteBlossom20 小时前
MySQL 面试场景题之如何处理 BLOB 和CLOB 数据类型?
数据库·mysql·面试
麦兜*20 小时前
MongoDB Atlas 云数据库实战:从零搭建全球多节点集群
java·数据库·spring boot·mongodb·spring·spring cloud
Slaughter信仰20 小时前
深入理解Java虚拟机:JVM高级特性与最佳实践(第3版)第十章知识点问答(10题)
java·jvm·数据库
麦兜*20 小时前
MongoDB 在物联网(IoT)中的应用:海量时序数据处理方案
java·数据库·spring boot·物联网·mongodb·spring