ClickHouse的GROUP BY子句
Group By子句又称聚合查询,与MySQL或者Hive中的使用方式一样,但是需要注意一点在Select查询中如果有聚合查询,例如max,min等,与聚合查询出现的字段一定要出现在Group by中,否则语句报错。
ClickHouse中的Group by 还可以配合WITH ROLLUP、WITH CUBE、WITH TOTALS三种修饰符获取额外的汇总信息。
创建表mt_tbl2 并加载数据:
代码语言:javascript复制#创建表mt_tbl2
node1 :) CREATE TABLE mt_tbl2
(
`province` String,
`city` String,
`item` String,
`totalcount` UInt32
)
ENGINE = MergeTree()
ORDER BY (province, city)
#向表中插入如下数据:
node1 :) insert into mt_tbl2 values ('北京','海淀','苹果手机',100),('上海','黄浦','小米手机',200),('北京','丰台','苹果手机',300),('北京','大兴','华为手机',400),('上海','嘉定','华为手机',500),('
北京','海淀','华为手机',600),('上海','黄浦','小米手机',700),('北京','大兴','苹果手机',800),('上海','嘉定','华为手机',900),('北京','海淀','小米手机',1000);
一、WITH ROLLUP
ROLLUP 能够按照聚合键从右向左上卷数据,基于聚合函数依次生成分组小计和总计。操作如下:
代码语言:javascript复制node1 :) select province,city,item,sum(totalcount) as total from mt_tbl2 group by province,city,item with rollup;
二、WITH CUBE
CUBE 是立方体意思,WITH CUBE会基于聚合键之间所有的组合生成小计信息。操作如下:
代码语言:javascript复制node1 :) select province,city,item,sum(totalcount) as total from mt_tbl2 group by province,city,item with cube;
三、WITH TOTALS
WITH TOTALS 会基于聚合键生成结果外,还会附带一行Totals汇总统计。操作如下:
代码语言:javascript复制node1 :) select province,city,item,sum(totalcount) as total from mt_tbl2 group by province,city,item with totals;