#成为 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 辅助

相关推荐
库库林_沙琪马1 小时前
Redis 持久化:从零到掌握
数据库·redis·缓存
牵牛老人2 小时前
Qt中使用QPdfWriter类结合QPainter类绘制并输出PDF文件
数据库·qt·pdf
卡西里弗斯奥4 小时前
【达梦数据库】dblink连接[SqlServer/Mysql]报错处理
数据库·mysql·sqlserver·达梦
温柔小胖5 小时前
sql注入之python脚本进行时间盲注和布尔盲注
数据库·sql·网络安全
杨俊杰-YJ5 小时前
MySQL 主从复制原理及其工作过程
数据库·mysql
一个儒雅随和的男子6 小时前
MySQL的聚簇索引与非聚簇索引
数据库·mysql
£漫步 云端彡6 小时前
技术分享:MyBatis SQL 日志解析脚本
java·sql·mybatis 日志解析
2301_793069827 小时前
Java和SQL测试、性能监控中常用工具
java·sql·selenium
V+zmm101348 小时前
基于微信小程序的家政服务预约系统的设计与实现(php论文源码调试讲解)
java·数据库·微信小程序·小程序·毕业设计
roman_日积跬步-终至千里8 小时前
【分布式理论14】分布式数据库存储:分表分库、主从复制与数据扩容策略
数据库·分布式