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

相关推荐
无毁的湖光-Al2 小时前
解Bug之路-隔离故障点后业务不恢复?-热点Key处理与亚稳态故障
java·数据库·mysql
l1t3 小时前
DeepSeek总结的有符号、无符号、未对齐:从汇编到 SQL 的教训
汇编·数据库·sql
夜雪一千3 小时前
MySQL 如何提高查询速度:从索引、SQL、表结构到实战调优
android·sql·mysql
麦壳饼3 小时前
SonnetDB SQL Cookbook:常用查询模式速查
数据库·sonnetdb
for_ever_love__4 小时前
LangChain Text-to-SQL:让不会写 SQL 的人查数据库
数据库·sql·langchain·大模型·agent·rag·问答
梦想不只是梦与想4 小时前
SQLAlchemy:查询与操作 (三)
数据库·python·sqlalchemy
Aric_Jones4 小时前
WAL / CDC / 复制槽 /位点
数据库·oracle
草莓熊Lotso4 小时前
【C++ 基于微服务的即时通讯系统】基建三件套:gflags + gtest + spdlog 源码编译安装与实战入门
linux·网络·数据库·c++·微服务·log4j
bksczm4 小时前
Redis基础篇之初识分布式
数据库·redis·分布式
for_ever_love__4 小时前
MySQL 索引类型全解:B+Tree / Hash / R-Tree / 全文 的底层差异,以及一次性建对的选型表
数据库·mysql·b+树·唯一索引·全文索引·索引类型·索引分类