clickhouse21.7.11.3 SQL-LIMIT BY子句

说明

在ClickHouse里,增加了下面子句:

limit n by expressions

根据 by 字段 的值,每个值保留 前 n 行记录

例子

drop table t_student_mt2
create table t_student_mt2
(
    sid UInt32,
    name String,
    age int,
    create_time Datetime
)
engine = MergeTree
partition by toYYYYMMDD(create_time)
PRIMARY KEY (sid)
order by (sid,age);
insert into t_student_mt2 values 
(1,'lucy',22,'2022-01-02 09:30:00'),
(2,'lili',22,'2022-01-02 09:50:00'),
(3,'张三',21,'2022-01-02 09:50:00'),
(4,'韩梅梅',21,'2022-01-01 09:30:00'),
(5,'李雷',20,'2022-01-01 09:30:00');
select * from t_student_mt2 order by create_time desc limit 1 by age

执行结果如下:

sid name age create_time
4 张三 21 2022-01-02 09:50:00
4 lili 22 2022-01-02 09:50:00
2 李雷 20 2022-01-01 09:30:00

解释:根据 create_time 倒序查询,每个 age 的值,只保留 前1条 数据

语法变体

根据 by 字段 的值,每个值,跳过 offset_value 条记录,保留 前 n 行记录

  • LIMIT [offset_value, ]n BY expressions
  • LIMIT n OFFSET offset_value BY expressions

例子

select * from t_student_mt2 order by create_time desc limit 1,1 by age

执行结果如下:

sid name age create_time
1 lucy 22 2022-01-02 09:30:00
2 韩梅梅 21 2022-01-01 09:30:00

解释:根据 create_time 倒序查询,每个 age 的值,跳过前1条记录,然后只保留 前1条 数据

参考:
https://www.gbase8.cn/5237


原文出处:/show_1IX3R5iAdN7u.html