SQL 实战
日期序列表
SQL 语句:
select
date_format(d.day, '%Y-%m-d')
from unnest(sequence(timestamp '2018-01-01 00:00:00', timestamp '2018-01-07 00:00:00', interval '1' day)) as d (day)
查询结果:
2018-01-01
2018-01-02
2018-01-03
2018-01-04
2018-01-05
2018-01-06
2018-01-07
除零处理
SQL 语句:
select coalesce(try(1/0), 0)
查询结果:
0
使用 with 命名查询
with
u as (
select
*
from user
)
select * from u
数据抽样
按抽样率抽样:
select
*
from users tablesample bernoulli (50);
select
*
from users tablesample system (75);
参考:https://prestodb.io/docs/current/sql/select.html
按数量抽样:
select
*
from users
order by rand()
limit 100;
SQL 优化
分组字段顺序
使用多个字段作为分组条件,基数大的字段在前,基数小的字段在后,举个🌰:
group by gender, user_id // bad
group by user_id, gender // good
多个 LIKE 条件
合并多个 LIKE 条件为一个 regexp_like 条件,举个🌰:
method LIKE '%GET%' OR
method LIKE '%POST%' OR
method LIKE '%PUT%' OR
method LIKE '%DELETE%' // bad
regexp_like(method, 'GET|POST|PUT|DELETE') // good
提示:以上 SQL 运行在 Presto 0.166 版本