clickhouse日期函数

转载:日期函数

参考:ck官网

  1 Clickhouse 时间日期函数
  2 
  3     注:所有的时间日期函数都可以在第二个可选参数中接受时区参数。示例:Asia / Yekaterinburg。在这种情况下,它们使用指定的时区而不是本地(默认)时区。
  4 
  5     SELECT
  6         toDateTime('2016-06-15 23:00:00') AS time,
  7         toDate(time) AS date_local,
  8         toDate(time, 'Asia/Yekaterinburg') AS date_yekat,
  9         toString(time, 'US/Samoa') AS time_samoa
 10 
 11     ┌────────────────time─┬─date_local─┬─date_yekat─┬─time_samoa──────────┐
 122016-06-15 23:00:002016-06-152016-06-162016-06-15 09:00:00 13     └─────────────────────┴────────────┴────────────┴─────────────────────┘
 14 
 15  
 16 常用时间函数:
 17 
 18     now()                // 2020-04-01 17:25:40     取当前时间
 19     toYear()             // 2020                    取日期中的年份
 20     toMonth()            // 4                       取日期中的月份
 21     today()              // 2020-04-01              今天的日期
 22     yesterday()          // 2020-03-31              昨天的额日期
 23     toDayOfYear()        // 92                      取一年中的第几天     
 24     toDayOfWeek()        // 3                       取一周中的第几天
 25     toHour()             //17                       取小时
 26     toMinute()           //25                       取分钟
 27     toSecond()           //40                       取秒
 28     toStartOfYear()      //2020-01-01               取一年中的第一天
 29     toStartOfMonth()     //2020-04-01               取当月的第一天
 30      
 31     formatDateTime(now(),'%Y-%m-%d')        // 2020*04-01         指定时间格式
 32     toYYYYMM()                              //202004              
 33     toYYYYMMDD()                            //20200401
 34     toYYYYMMDDhhmmss()                      //20200401172540
 35     dateDiff()
 36     ......
 37 
 38     SELECT
 39         toDateTime('2019-07-30 10:10:10') AS time,  
 40        
 41         -- 将DateTime转换成Unix时间戳
 42         toUnixTimestamp(time) as unixTimestamp,  
 43           
 44         -- 保留 时-分-秒
 45         toDate(time) as date_local,
 46         toTime(time) as date_time,   -- 将DateTime中的日期转换为一个固定的日期,同时保留时间部分。
 47      
 48         -- 获取年份,月份,季度,小时,分钟,秒钟
 49         toYear(time) as get_year,
 50         toMonth(time) as get_month,
 51      
 52         -- 一年分为四个季度。1(一季度:1-3),2(二季度:4-6),3(三季度:7-9),4(四季度:10-12)
 53         toQuarter(time) as get_quarter,
 54         toHour(time) as get_hour,
 55         toMinute(time) as get_minute,
 56         toSecond(time) as get_second,
 57      
 58         -- 获取 DateTime中的当前日期是当前年份的第几天,当前月份的第几日,当前星期的周几
 59         toDayOfYear(time) as "当前年份中的第几天",
 60         toDayOfMonth(time) as "当前月份的第几天",
 61         toDayOfWeek(time) as "星期",
 62         toDate(time, 'Asia/Shanghai') AS date_shanghai,
 63         toDateTime(time, 'Asia/Shanghai') AS time_shanghai,
 64      
 65         -- 得到当前年份的第一天,当前月份的第一天,当前季度的第一天,当前日期的开始时刻
 66         toStartOfYear(time),
 67         toStartOfMonth(time),
 68         toStartOfQuarter(time),
 69         toStartOfDay(time) AS cur_start_daytime,
 70         toStartOfHour(time) as cur_start_hour,
 71         toStartOfMinute(time) AS cur_start_minute,
 72      
 73         -- 从过去的某个固定的时间开始,以此得到当前指定的日期的编号
 74         toRelativeYearNum(time),
 75         toRelativeQuarterNum(time);
 76 
 77 获取未来时间的函数:
 78 
 79     -- 第一种,日期格式(指定日期,需注意时区的问题)
 80     WITH
 81         toDate('2019-09-09') AS date,
 82         toDateTime('2019-09-09 00:00:00') AS date_time
 83     SELECT
 84         addYears(date, 1) AS add_years_with_date,
 85         addYears(date_time, 0) AS add_years_with_date_time;
 86      
 87     -- 第二种,日期格式(当前,本地时间)
 88     WITH
 89         toDate(now()) as date,
 90         toDateTime(now()) as date_time
 91     SELECT
 92         now() as now_time,-- 当前时间
 93         -- 之后1年
 94         addYears(date, 1) AS add_years_with_date,                  
 95         addYears(date_time, 1) AS add_years_with_date_time,
 96         
 97         -- 之后1月
 98         addMonths(date, 1) AS add_months_with_date,                 
 99         addMonths(date_time, 1) AS add_months_with_date_time,
100      
101         --之后1周
102         addWeeks(date, 1) AS add_weeks_with_date,                   
103         addWeeks(date_time, 1) AS add_weeks_with_date_time,
104      
105         -- 之后1天
106         addDays(date, 1) AS add_days_with_date,                     
107         addDays(date_time, 1) AS add_days_with_date_time,
108      
109         --之后1小时
110         addHours(date_time, 1) AS add_hours_with_date_time,  
111         
112         --之后1分中       
113         addMinutes(date_time, 1) AS add_minutes_with_date_time,
114      
115         -- 之后10秒钟     
116         addSeconds(date_time, 10) AS add_seconds_with_date_time,
117         
118          -- 之后1个季度    
119         addQuarters(date, 1) AS add_quarters_with_date,            
120         addQuarters(date_time, 1) AS add_quarters_with_date_time;
121 
122 获取过去时间的函数:
123 
124     WITH
125         toDate(now()) as date,
126         toDateTime(now()) as date_time
127     SELECT
128         subtractYears(date, 1) AS subtract_years_with_date,
129         subtractYears(date_time, 1) AS subtract_years_with_date_time,
130         subtractQuarters(date, 1) AS subtract_Quarters_with_date,
131         subtractQuarters(date_time, 1) AS subtract_Quarters_with_date_time,
132         subtractMonths(date, 1) AS subtract_Months_with_date,
133         subtractMonths(date_time, 1) AS subtract_Months_with_date_time,
134         subtractWeeks(date, 1) AS subtract_Weeks_with_date,
135         subtractWeeks(date_time, 1) AS subtract_Weeks_with_date_time,
136         subtractDays(date, 1) AS subtract_Days_with_date,
137         subtractDays(date_time, 1) AS subtract_Days_with_date_time,
138         subtractHours(date_time, 1) AS subtract_Hours_with_date_time,
139         subtractMinutes(date_time, 1) AS subtract_Minutes_with_date_time,
140         subtractSeconds(date_time, 1) AS subtract_Seconds_with_date_time;
141      
142     SELECT toDate('2019-07-31', 'Asia/GuangZhou') as date_guangzhou;
143     SELECT toDate('2019-07-31'), toDate('2019-07-31', 'Asia/Beijing') as date_beijing;
144      
145     -- 亚洲只能加载上海的timezone???
146     SELECT toDateTime('2019-07-31 10:10:10', 'Asia/Shanghai') as date_shanghai;
147 
148 计算连个时刻在不同时间单位下的差值
149 
150     -- 第一种:指定时间计算差值示例
151     WITH
152         toDateTime('2019-07-30 10:10:10', 'Asia/Shanghai') as date_shanghai_one,
153         toDateTime('2020-10-31 11:20:30', 'Asia/Shanghai') as date_shanghai_two
154     SELECT
155         dateDiff('year', date_shanghai_one, date_shanghai_two) as diff_years,
156         dateDiff('month', date_shanghai_one, date_shanghai_two) as diff_months,
157         dateDiff('week', date_shanghai_one, date_shanghai_two) as diff_week,
158         dateDiff('day', date_shanghai_one, date_shanghai_two) as diff_days,
159         dateDiff('hour', date_shanghai_one, date_shanghai_two) as diff_hours,
160         dateDiff('minute', date_shanghai_one, date_shanghai_two) as diff_minutes,
161         dateDiff('second', date_shanghai_one, date_shanghai_two) as diff_seconds;
162      
163     -- 第二种:本地当前时间示例
164     WITH
165         now() as date_time
166     SELECT
167         dateDiff('year', date_time, addYears(date_time, 1)) as diff_years,
168         dateDiff('month', date_time, addMonths(date_time, 2)) as diff_months,
169         dateDiff('week', date_time, addWeeks(date_time, 3)) as diff_week,
170         dateDiff('day', date_time, addDays(date_time, 3)) as diff_days,
171         dateDiff('hour', date_time, addHours(date_time, 3)) as diff_hours,
172         dateDiff('minute', date_time, addMinutes(date_time, 30)) as diff_minutes,
173         dateDiff('second', date_time, addSeconds(date_time, 35)) as diff_seconds;

   1 -------------------------------------------------
   2 --------------------------------------------------
   3 ---------------Clickhouse基础知识:函数学习-------------
   4 --官址学习文档:https://clickhouse.yandex/docs/zh/
   5 --------------------------------------------------
   6 --------------------------------------------------
   7 
   8  
   9 
  10 
  11 ----------------------------------------------------------------------------
  12 -- DBeaver6.1.2操作快捷键:
  13 -- 常用快捷键须知:(Ctrl + Shift + L 显示快捷键列表)
  14 -- 1.删除光标所在行:Ctrl + D
  15 -- 2.复制光标所在行:Ctrl + Alt + ↓
  16 -- 3.移动光标所在行:Ctrl + Shift + ↑/↓
  17 -- 4.缩小SQL编辑器的文本字体大小:Ctrl + -/+
  18 -- 5.查找:Ctrl + F
  19 -- 6.选中上或下的SQL执行语句:Alt + ↑/↓
  20 -- 7.执行当前光标所在SQL语句(无论是否格式化过,前提是此SQL语句和上一条有空行或者上一条SQL语句有分号“;”隔开)
  21 ----------------------------------------------------------------------------
  22 
  23 -- 零、检测函数类型(clickhouse中数据的类型)
  24 SELECT toTypeName(0);-- UInt8(三位数为8)
  25 SELECT toTypeName(-0);-- Int8
  26 SELECT toTypeName(-343);-- Int16
  27 SELECT toTypeName(12.43); -- Float64(默认浮点型的数据为64),所以一般在处理浮点型的数据的时候尽量转成toFloat32(12.43)
  28 SELECT toTypeName(12.34343); -- Float64
  29 SELECT toTypeName(toDateTime(1502396027)); -- DateTime
  30 
  31 -- 一、算数函数
  32 -->>>>>> 算数函数(数学上的计算)
  33 --求和
  34 SELECT plus(12, 21), plus(10, -10), plus(-10, -10);
  35 --差值
  36 SELECT minus(10, 5), minus(10, -10),minus(-10, -10);
  37 --
  38 SELECT multiply(12, 2), multiply(12, -2), multiply(-12, -2);
  39 --平均值
  40 SELECT divide(12, 4), divide(10, 3), divide(2, 4), divide(-4, -2), divide(-4, 2), divide(-4.5, 3);
  41 SELECT intDiv(10, 3), divide(10, 3); -- 3, 3.333(保留四位有效数字)
  42 SELECT divide(10, 0), divide(-10, 0); -- 出现无穷大字符“ ∞ ”或“ -∞ ”
  43 SELECT divide(0, 0); -- 特殊字符(类似乱码)
  44 SELECT intDivOrZero(10, 0); -- 0
  45 --求余数
  46 SELECT modulo(10, 3); --1
  47 SELECT modulo(10.5, 3); --1
  48 --取反
  49 SELECT negate(10), negate(-10); -- -10 10
  50 --绝对值
  51 SELECT abs(-10), abs(10);
  52 --最大公约数
  53 SELECT gcd(12, 24), gcd(-12, -24), gcd(-12, 24);
  54 --最小公倍数
  55 SELECT lcm(12, 24), lcm(-12, -24), lcm(-3, 4);
  56 
  57 -- 二、比较函数
  58 -->>>>>> 比较函数(始终返回0表示false 或 1表示true)
  59 SELECT 12 == 12, 12 != 10, 12 == 132, 12 != 12, 12 <> 12;
  60 SELECT equals(12, 12), notEquals(12, 10), equals(12, 10), notEquals(12,123);
  61 SELECT greater(12, 10), greater(10, 12), greater(12, 12);-- 前者是否大于后者
  62 SELECT greaterOrEquals(12,10), greaterOrEquals(12,12);-- 前者是否大于或等于后者
  63 SELECT less(12, 21), less(12, 10), less(120, 120);-- 前者是否小于后者
  64 SELECT lessOrEquals(12, 120), lessOrEquals(12, 12);-- 前世是否小于或等于或者
  65 
  66 -- 三、逻辑函数
  67 -->>>>>> 逻辑操作符(返回0表示false 或 1表示true)
  68 SELECT 12==12 or 12!=10;
  69 SELECT 12==12 and 12!=10;
  70 SELECT not 12, not 0;
  71 SELECT or(equals(12, 12), notEquals(12, 10)); --函数表示法:或
  72 SELECT and(equals(12, 12), notEquals(12, 10));--函数表示法:且
  73 SELECT not(12), not(0);
  74 
  75 -- 四、类型转换函数
  76 -->>>>>> 类型转换函数部分示例:
  77 SELECT toInt8(12.3334343), toFloat32(10.001), toFloat64(1.000040);
  78 SELECT toString(now());
  79 SELECT now() AS now_local, toString(now(), 'Asia/Yekaterinburg') AS now_yekat;
  80 SELECT now() AS now_local, toDate(now()), toDateTime(now()), toUnixTimestamp(now());
  81 
  82 SELECT
  83 '2016-06-15 23:00:00' AS timestamp,
  84 CAST(timestamp AS DateTime) AS datetime,
  85 CAST(timestamp AS Date) AS date,
  86 CAST(timestamp, 'String') AS string,
  87 CAST(timestamp, 'FixedString(22)') AS fixed_string;
  88 
  89 WITH
  90 toDate('2019-01-01') AS date,
  91 INTERVAL 1 WEEK AS interval_week,
  92 toIntervalWeek(1) AS interval_to_week,
  93 toIntervalMonth(1) AS interval_to_month
  94 SELECT
  95 date + interval_week,
  96 date + interval_to_week,
  97 date + interval_to_month;
  98 
  99 WITH
 100 toDateTime('2019-01-01 12:10:10') as datetime,
 101 INTERVAL 1 HOUR AS interval_hour,
 102 toIntervalHour(1) as invterval_to_hour
 103 SELECT
 104 plus(datetime, interval_hour),
 105 plus(datetime, invterval_to_hour);
 106 
 107 -- 五、时间日期函数
 108 --->>>>>> 时间日期函数
 109 SELECT
 110 toDateTime('2019-07-30 10:10:10') AS time,
 111 -- 将DateTime转换成Unix时间戳
 112 toUnixTimestamp(time) as unixTimestamp,
 113 -- 保留 时-分-秒
 114 toDate(time) as date_local,
 115 toTime(time) as date_time,-- 将DateTime中的日期转换为一个固定的日期,同时保留时间部分。
 116 -- 获取年份,月份,季度,小时,分钟,秒钟
 117 toYear(time) as get_year,
 118 toMonth(time) as get_month,
 119 -- 一年分为四个季度。1(一季度:1-3),2(二季度:4-6),3(三季度:7-9),4(四季度:10-12)
 120 toQuarter(time) as get_quarter,
 121 toHour(time) as get_hour,
 122 toMinute(time) as get_minute,
 123 toSecond(time) as get_second,
 124 -- 获取 DateTime中的当前日期是当前年份的第几天,当前月份的第几日,当前星期的周几
 125 toDayOfYear(time) as "当前年份中的第几天",
 126 toDayOfMonth(time) as "当前月份的第几天",
 127 toDayOfWeek(time) as "星期",
 128 toDate(time, 'Asia/Shanghai') AS date_shanghai,
 129 toDateTime(time, 'Asia/Shanghai') AS time_shanghai,
 130 -- 得到当前年份的第一天,当前月份的第一天,当前季度的第一天,当前日期的开始时刻
 131 toStartOfYear(time),
 132 toStartOfMonth(time),
 133 toStartOfQuarter(time),
 134 toStartOfDay(time) AS cur_start_daytime,
 135 toStartOfHour(time) as cur_start_hour,
 136 toStartOfMinute(time) AS cur_start_minute,
 137 -- 从过去的某个固定的时间开始,以此得到当前指定的日期的编号
 138 toRelativeYearNum(time),
 139 toRelativeQuarterNum(time);
 140 
 141 SELECT
 142 toDateTime('2019-07-30 14:27:30') as time,
 143 toISOYear(time) AS iso_year,
 144 toISOWeek(time) AS iso_week,
 145 now() AS cur_dateTime1, -- 返回当前时间yyyy-MM-dd HH:mm:ss
 146 today() AS cur_dateTime2, -- 其功能与'toDate(now())'相同
 147 yesterday() AS yesterday, -- 当前日期的上一天
 148 -- timeSlot(1) AS timeSlot_1, -- 出现异常!!将时间向前取整半小时
 149 toDate(time) as getY_M_d;
 150 
 151 -- 目前只有这三种格式,没有什么toYYYY(),toYYYddmm()之类的函数,不要想当然。
 152 SELECT
 153 now() as nowTime,
 154 -- 将Date或DateTime转换为包含年份和月份编号的UInt32类型的数字(YYYY * 100 + MM)
 155 toYYYYMMDDhhmmss(nowTime),
 156 toYYYYMMDD(nowTime),
 157 toYYYYMM(nowTime);
 158 
 159 -- formatDateTime(Time, Format[,Timezone])函数引用
 160 SELECT
 161 now() as now_time,
 162 toDateTime('2019-07-31 18:20:30') AS def_datetime,
 163 formatDateTime(now_time, '%D') AS now_time_day_month_year,-- 07/30/19
 164 -- toDateTime('2019-07-31 18:20:30', 'Asia/Shanghai') AS def_datetime1, -- 指定时区
 165 formatDateTime(def_datetime, '%Y') AS def_datetime_year, -- 2019(指定日期为2019年)
 166 formatDateTime(def_datetime, '%y') AS def_datetime_year_litter, -- 19(指定日期为19年,Year, last two digits (00-99),本世纪的第19年)
 167 formatDateTime(def_datetime, '%H') AS hour24, -- 18 下午六点
 168 formatDateTime(def_datetime, '%I') AS hour12, -- 06下午六点
 169 formatDateTime(def_datetime, '%p') AS PMorAM, -- 指定时间是上午还是下午
 170 formatDateTime(def_datetime, '%w') AS def_datetime_get_curWeek,-- 3(指定日期为星期三)
 171 formatDateTime(def_datetime, '%F') AS def_datetime_get_date,-- 2019-07-31
 172 formatDateTime(def_datetime, '%T') AS def_datetime_get_time,-- 18:20:30
 173 formatDateTime(def_datetime, '%M') AS def_datetime_get_minute,-- 20(得到指定事件的“分”,minute (00-59))
 174 formatDateTime(def_datetime, '%S') AS def_datetime_get_second;-- 30(得到指定事件的“秒”,second (00-59))
 175 
 176  
 177 
 178 -- 1.跳转到之后的日期函数
 179 -- 第一种,日期格式(指定日期,需注意时区的问题)
 180 WITH
 181 toDate('2019-09-09') AS date,
 182 toDateTime('2019-09-09 00:00:00') AS date_time
 183 SELECT
 184 addYears(date, 1) AS add_years_with_date,
 185 addYears(date_time, 0) AS add_years_with_date_time;
 186 -- 第二种,日期格式(当前,本地时间)
 187 WITH
 188 toDate(now()) as date,
 189 toDateTime(now()) as date_time
 190 SELECT
 191 now() as now_time,-- 当前时间
 192 addYears(date, 1) AS add_years_with_date,-- 之后1年
 193 addYears(date_time, 1) AS add_years_with_date_time,
 194 addMonths(date, 1) AS add_months_with_date,-- 之后1月
 195 addMonths(date_time, 1) AS add_months_with_date_time,
 196 addWeeks(date, 1) AS add_weeks_with_date,--之后1周
 197 addWeeks(date_time, 1) AS add_weeks_with_date_time,
 198 addDays(date, 1) AS add_days_with_date,-- 之后1天
 199 addDays(date_time, 1) AS add_days_with_date_time,
 200 addHours(date_time, 1) AS add_hours_with_date_time,--之后1小时
 201 addMinutes(date_time, 1) AS add_minutes_with_date_time,--之后1分中
 202 addSeconds(date_time, 10) AS add_seconds_with_date_time,-- 之后10秒钟
 203 addQuarters(date, 1) AS add_quarters_with_date, -- 之后1个季度
 204 addQuarters(date_time, 1) AS add_quarters_with_date_time;
 205 
 206 -- 2.跳转到当前日期之前的函数(函数将Date/DateTime减去一段时间间隔,然后返回Date/DateTime)
 207 WITH
 208 toDate(now()) as date,
 209 toDateTime(now()) as date_time
 210 SELECT
 211 subtractYears(date, 1) AS subtract_years_with_date,
 212 subtractYears(date_time, 1) AS subtract_years_with_date_time,
 213 subtractQuarters(date, 1) AS subtract_Quarters_with_date,
 214 subtractQuarters(date_time, 1) AS subtract_Quarters_with_date_time,
 215 subtractMonths(date, 1) AS subtract_Months_with_date,
 216 subtractMonths(date_time, 1) AS subtract_Months_with_date_time,
 217 subtractWeeks(date, 1) AS subtract_Weeks_with_date,
 218 subtractWeeks(date_time, 1) AS subtract_Weeks_with_date_time,
 219 subtractDays(date, 1) AS subtract_Days_with_date,
 220 subtractDays(date_time, 1) AS subtract_Days_with_date_time,
 221 subtractHours(date_time, 1) AS subtract_Hours_with_date_time,
 222 subtractMinutes(date_time, 1) AS subtract_Minutes_with_date_time,
 223 subtractSeconds(date_time, 1) AS subtract_Seconds_with_date_time;
 224 
 225 SELECT toDate('2019-07-31', 'Asia/GuangZhou') as date_guangzhou;
 226 SELECT toDate('2019-07-31'), toDate('2019-07-31', 'Asia/Beijing') as date_beijing;
 227 -- 亚洲只能加载上海的timezone???
 228 SELECT toDateTime('2019-07-31 10:10:10', 'Asia/Shanghai') as date_shanghai;
 229 
 230 
 231 -- 计算连个时刻在不同时间单位下的差值
 232 -- 第一种:指定时间计算差值示例
 233 WITH
 234 toDateTime('2019-07-30 10:10:10', 'Asia/Shanghai') as date_shanghai_one,
 235 toDateTime('2020-10-31 11:20:30', 'Asia/Shanghai') as date_shanghai_two
 236 SELECT
 237 dateDiff('year', date_shanghai_one, date_shanghai_two) as diff_years,
 238 dateDiff('month', date_shanghai_one, date_shanghai_two) as diff_months,
 239 dateDiff('week', date_shanghai_one, date_shanghai_two) as diff_week,
 240 dateDiff('day', date_shanghai_one, date_shanghai_two) as diff_days,
 241 dateDiff('hour', date_shanghai_one, date_shanghai_two) as diff_hours,
 242 dateDiff('minute', date_shanghai_one, date_shanghai_two) as diff_minutes,
 243 dateDiff('second', date_shanghai_one, date_shanghai_two) as diff_seconds;
 244 
 245 -- 第二种:本地当前时间示例
 246 WITH
 247 now() as date_time
 248 SELECT
 249 dateDiff('year', date_time, addYears(date_time, 1)) as diff_years,
 250 dateDiff('month', date_time, addMonths(date_time, 2)) as diff_months,
 251 dateDiff('week', date_time, addWeeks(date_time, 3)) as diff_week,
 252 dateDiff('day', date_time, addDays(date_time, 3)) as diff_days,
 253 dateDiff('hour', date_time, addHours(date_time, 3)) as diff_hours,
 254 dateDiff('minute', date_time, addMinutes(date_time, 30)) as diff_minutes,
 255 dateDiff('second', date_time, addSeconds(date_time, 35)) as diff_seconds;
 256 
 257 -- timeSlot(StartTime, Duration, [,Size])
 258 -- 它返回一个时间数组,其中包括从从“StartTime”开始到“StartTime + Duration 秒”内的所有符合“size”(以秒为单位)步长的时间点
 259 -- 作用:搜索在相应会话中综合浏览量是非常有用的。
 260 SELECT
 261 timeSlots(toDateTime('2012-01-01 12:20:00'), toUInt32(600)) as dateTimeArray,
 262 dateTimeArray[0] as arr_index_0, -- no result.
 263 dateTimeArray[1] as arr_index_1, -- 2012-01-01 20:00:00
 264 dateTimeArray[2] as arr_index_2, -- 2012-01-01 20:30:00
 265 dateTimeArray[3] as arr_index_3, -- no result.
 266 dateTimeArray[4] as arr_index_4; -- no result.
 267 -- toUInt32(600) 表示之后间距20秒的时刻
 268 SELECT
 269 timeSlots(now(), toUInt32(600), 20) as dateTimeArray, -- 类似于:引用地址
 270 dateTimeArray[0] as arr_index_0, -- no result.为什么?
 271 dateTimeArray[1] as arr_index_1,
 272 dateTimeArray[2] as arr_index_2,
 273 dateTimeArray[3] as arr_index_3,
 274 dateTimeArray[4] as arr_index_4,
 275 dateTimeArray[5] as arr_index_5;
 276 -- 指定时间为基准,之后每个元素增加20秒
 277 SELECT
 278 timeSlots(toDateTime('2012-01-01 12:20:00'), toUInt32(600), 20) as cur_dateTimeArray, -- 类似于:引用地址
 279 cur_dateTimeArray[0] as arr_index_0, -- no result.为什么?
 280 cur_dateTimeArray[1] as arr_index_1, -- 2012-01-01 20:20:00
 281 cur_dateTimeArray[2] as arr_index_2, -- 2012-01-01 20:20:20
 282 cur_dateTimeArray[3] as arr_index_3, -- 2012-01-01 20:20:40
 283 cur_dateTimeArray[4] as arr_index_4, -- 2012-01-01 20:21:00
 284 cur_dateTimeArray[5] as arr_index_5; -- 2012-01-01 20:21:20
 285 
 286 
 287 -- 六、字符串函数
 288 --->>>>>> 字符串函数:
 289 SELECT
 290 length('hello world') as str_length, -- 按照Unicode编码计算长度“你好”的长度为6
 291 empty('hello world'),-- 判断字符串是否为空,空为1,非空为0
 292 notEmpty('hello world'),
 293 lengthUTF8('hello world'), -- 按照实际字符计算长度“你好”为2
 294 char_length('hello world'), -- 同 lengthUTF8()
 295 character_length('hello world'), -- 同 lengthUTF8(),
 296 lower('abcd123--'),--字母全部小写(将字符串中的ASCII转换为小写。)
 297 upper('abcd123--'),--字母全部大写(将字符串中的ASCII转换为大写。)
 298 lowerUTF8('abcd123-/*\8asd-\\'), -- abcd123-/*8asd-\
 299 upperUTF8('abcd123--'), -- ABCD123--
 300 isValidUTF8('abcd123--/*\*'); --检查字符串是否为有效的UTF-8编码,是则返回1,否则返回0。
 301 SELECT notEmpty(''), notEmpty(NULL), notEmpty('he'); -- 0,空,1
 302 SELECT toValidUTF8('\x61\xF0\x80\x80\x80b');
 303 -- reverseUTF8():以Unicode字符为单位反转UTF-8编码的字符串。如果字符串不是UTF-8编码,则可能获取到一个非预期的结果(不会抛出异常)
 304 SELECT reverse('abcdefg'), reverseUTF8('abcdefg');
 305 -- 2.字符串维度自定义安排
 306 SELECT format('{1} {0} {1}', 'World', 'Hello'); -- 输出:Hello World Hello
 307 SELECT format('{0} {0} {1} {1}', 'one', 'two'); -- 输出:one one two two
 308 SELECT format('{} {}', 'Hello', 'World'); -- 输出:Hello World
 309 -- 3.字符串拼接 concat(s1,s2,s3,...)
 310 SELECT concat('Hello',' ','World', '!');-- Hello World!
 311 -- 与concat相同,区别在于,你需要保证concat(s1, s2, s3) -> s4是单射的,它将用于GROUP BY的优化。
 312 SELECT concatAssumeInjective('Hello',' ','World', '!');-- Hello World!
 313 -- 4.字符串截取:substring(s, offset, length), mid(s, offset, length), substr(s, offset, length)
 314 -- 以字节为单位截取指定位置字符串,返回以‘offset’位置为开头,长度为‘length’的子串。‘offset’从1开始(与标准SQL相同)。‘offset’和‘length’参数必须是常量。
 315 SELECT
 316 substring('abcdefg', 1, 3),-- abc
 317 substring('你好,世界', 1, 3),--
 318 substringUTF8('你好,世界', 1, 3); -- 你好,
 319 -- 5.字符串拼接:appendTrailingCharIfAbsent(s, c)
 320 -- 如果‘s’字符串非空并且末尾不包含‘c’字符,则将‘c’字符附加到末尾。
 321 SELECT
 322 appendTrailingCharIfAbsent('good','c'), -- goodc
 323 appendTrailingCharIfAbsent('goodccc','c'); -- goodccc
 324 -- 6.字符串编码转换:convertCharset(s, from, to) 返回从‘from’中的编码转换为‘to’中的编码的字符串‘s’。
 325 SELECT
 326 convertCharset('hello', 'UTF8','Unicode'),-- ��h
 327 convertCharset('hello', 'Unicode', 'UTF8'),-- 桥汬�
 328 convertCharset('hello', 'Unicode', 'ASCII'),-- 
 329 convertCharset('hello', 'ascii', 'ascii'),--hello
 330 convertCharset('hello', 'UTF8','UTF8');-- hello
 331 SELECT
 332 base64Encode('username+password'),-- dXNlcm5hbWUrcGFzc3dvcmQ=
 333 base64Decode('dXNlcm5hbWUrcGFzc3dvcmQ='), -- username+password
 334 -- 使用base64将字符串解码成原始字符串。但如果出现错误,将返回空字符串。
 335 tryBase64Decode('dXNlcm5hbWUrcGFzc3dvcmQ=');
 336 -- 7.判断字符串是否已什么结尾或结束,返回1:true,0:flase
 337 -- endsWith(s, suffix) 返回是否以指定的后缀结尾。如果字符串以指定的后缀结束,则返回1,否则返回0
 338 -- startWith(s, prefix) 返回是否以指定的前缀开头。如果字符串以指定的前缀开头,则返回1,否则返回0。
 339 SELECT
 340 endsWith('string','g'),
 341 startsWith('string', 'str'); -- 1 true
 342 -- 8.删除左侧空白字符
 343 -- trimLeft(s) 返回一个字符串,用于删除左侧的空白字符
 344 -- trimRight(s) 返回一个字符串,用于删除右侧的空白字符
 345 -- trimBoth(s) 返回一个字符串,用于删除左侧和右侧的空白字符
 346 SELECT
 347 trimLeft(' sdfdgs'), -- sdfdgs
 348 trimRight('abcd '), -- abcd
 349 trimBoth(' abcd '); -- abcd
 350 
 351 -- 七、字符串搜索函数
 352 --->>>>>> 字符串搜索函数
 353 -- pasition(haystack, needle), 显示needle在haystack的第一个出现的位置。
 354 SELECT
 355 POSITION('2121stringstrstrstrstr','str') AS positionSearch, -- 5
 356 POSITION('你好,hello,12323-你好,你,好sdfd*dg', '你,好'),-- 31
 357 positionUTF8('n12你好','你好') AS positionUTF8,-- 4
 358 positionCaseInsensitive('ABCDCDEFABCD','bc') AS positionCaseInsensitive, --2
 359 locate('hellohellohellohello','ello'); -- 2
 360 -- multiSearchAllPositions(haystack, [needle1, needle2, ..., needlen])
 361 -- 注意:在所有multiSearch*函数中,由于实现规范,needles的数量应小于2^8。
 362 -- 函数返回一个数组,其中包含所有匹配needlei的位置
 363 SELECT
 364 multiSearchAllPositions('goodnamegoodnamegoodhellohihihi', ['dn', 'good']) as multiSearch,-- [4,1]
 365 multiSearchAllPositionsCaseInsensitive('nameSsdfagpSSDFDFetgfderef', ['SS','fa']) as multiCaseInsensitive,
 366 multiSearchAllPositionsUTF8('nameSsdfazz轴功率gpSSDFDFetgfderef', ['Ss','fa', 'zz轴']) AS multiSearchUTF8,
 367 multiSearchAllPositionsCaseInsensitiveUTF8('nameSsdfazz轴功率gpSSDFDFetgfderef', ['Ss','fa', 'zz轴']) AS multiCaseInsensitiveUTF8;
 368 -- 检查字符串是否与pattern正则表达式匹配。pattern可以是一个任意的re2正则表达式。 re2正则表达式的语法比Perl正则表达式的语法存在更多限制。
 369 -- match(haystack, pattern) 匹配到了则返回1,否则返回0
 370 SELECT
 371 match('1232434sadgaDDFSrefds', '[0-9a-zA-Z]'), -- 存在匹配的字符,返回1
 372 match('1232321', '[a-z]'); -- 不存在匹配的字符,返回0
 373 -- 与match相同,但如果所有正则表达式都不匹配,则返回0;如果任何模式匹配,则返回1。它使用hyperscan库。对于在字符串中搜索子字符串的模式,最好使用“multisearchany”,因为它更高效。
 374 -- multiMatchAny(haystack, [pattern1, pattern2, ..., patternn])
 375 -- 注意:任何haystack字符串的长度必须小于232字节,否则抛出异常。这种限制是因为hyperscan API而产生的。
 376 -- 多个正则表达式对原始字符进行匹配,如若只有一个正则表达式匹配上了则返回1,否则返回0
 377 SELECT
 378 multiMatchAny('abcABC',['[0-9]','[a-zA-Z]']) AS multiMatchAnyOne, -- 1
 379 multiMatchAny('123abcABC',['[0-9]','[a-zA-Z]']) AS multiMatchAnyTwo, --1
 380 -- 与multiMatchAny相同,但返回与haystack匹配的任何内容的索引位置。
 381 multiMatchAnyIndex('123abcABC', ['[0-9]','[a-zA-Z]']) as multiMatchAnyIndex; --2
 382 -- 模糊匹配:like()函数,注意大写敏感。
 383 -- % 表示任何字节数(包括零字符)
 384 -- _ 表示任何一个字节
 385 SELECT
 386 'hello' LIKE '%h%' as LIKE_UP, -- 1
 387 'hello' like 'he' AS like_low, -- 0
 388 'hello' not like 'he' AS not_like, -- 1
 389 'hello' like '%he%' AS like_litter, -- 1
 390 like('adgadgadfa1232', '_12_') AS like_func,
 391 like('sdfasdfasd', '[a-z]') AS like_func2, -- 0
 392 notLike('1232423', '[a-zA-Z]') AS not_like_func; -- 1
 393 -- 使用字符串截取字符串:extract(haystack, pattern)
 394 -- 使用正则表达式截取字符串。如果‘haystack’与‘pattern’不匹配,则返回空字符串。如果正则表达式中不包含子模式,它将获取与整个正则表达式匹配的子串。否则,它将获取与第一个子模式匹配的子串。
 395 SELECT
 396 extractAll('hellogoodaimantIdeaIDEAfasd123232', '[0-9]'), -- ['1','2','3','2','3','2']
 397 extractAll('12323dSDFRE', '[A-Z]'),-- ['S','D','F','R','E']
 398 extract('helloclickhouse', '[a-z]');-- h
 399 -- ngramSearch(haystack, needle)
 400 -- 基于4-gram计算haystack和needle之间的距离:计算两个4-gram集合之间的对称差异,并用它们的基数和对其进行归一化。
 401 -- 返回0到1之间的任何浮点数 -- 越接近0则表示越多的字符串彼此相似。
 402 -- 如果常量的needle或haystack超过32KB,函数将抛出异常。如果非常量的haystack或needle字符串超过32Kb,则距离始终为1。
 403 SELECT
 404 ngramDistance('hello123456789','123') AS ngramDistance,
 405 ngramDistanceCaseInsensitive('hello123456789','123') AS ngramDistanceCaseInsensitive,
 406 ngramDistanceUTF8('hello123456789','123') AS ngramDistanceUTF8,
 407 ngramDistanceCaseInsensitiveUTF8('hello123456789','123') AS ngramDistanceCaseInsensitiveUTF8;
 408 -- 注意:对于UTF-8,我们使用3-gram。所有这些都不是完全公平的n-gram距离。
 409 -- 我们使用2字节哈希来散列n-gram,然后计算这些哈希表之间的(非)对称差异 - 可能会发生冲突。
 410 -- 对于UTF-8不区分大小写的格式,我们不使用公平的tolower函数
 411 -- 我们将每个Unicode字符字节的第5位(从零开始)和字节的第一位归零
 412 -- 这适用于拉丁语,主要用于所有西里尔字母。
 413 
 414 --八、字符串替换函数
 415 --->>>>>> 字符串替换函数
 416 -- 替换匹配到的字符串
 417 -- replaceOne(haystack, pattern, replacement)
 418 -- 用‘replacement’子串替换‘haystack’中与‘pattern’子串第一个匹配的匹配项(如果存在)。 ‘pattern’和‘replacement’必须是常量。
 419 -- replaceAll(haystack, pattern, replacement), replace(haystack, pattern, replacement)
 420 -- 用‘replacement’子串替换‘haystack’中出现的所有‘pattern’子串。
 421 SELECT
 422 replaceOne('hed1234544', '4', '*') AS replaceOne,-- hed123*544
 423 replaceRegexpOne('hed1234544', '4', '*') AS replaceRegexpOne,-- hed123*544
 424 replace('hed1234544', '4', '*') AS replace, -- hed123*5**
 425 replaceAll('hed1234544', '4', '*') AS replaceAll;-- hed123*5**
 426 
 427 -- 实例:2019-07-31 改变成 07/31/2019
 428 SELECT
 429 toDate(now()) AS now_date,
 430 replaceRegexpOne(toString(now_date), '(\\d{4})-(\\d{2})-(\\d{2})', '\\2/\\3/\\1') AS format_date;
 431 -- 示例:赋值字符串10次
 432 SELECT replaceRegexpOne('Hello, World!', '.*', '\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0') AS res;
 433 -- replaceRegexpAll(haystack, pattern, replacement)
 434 -- 与replaceRegexpOne相同,但会替换所有出现的匹配项。例如:
 435 SELECT replaceRegexpAll('hello,world!', '.', '\\0\\0') as res; -- hheelllloo,,wwoorrlldd!!
 436 SELECT replaceRegexpAll('hello o o, world.', ' ', '*') as res; -- hello*o*o,*world.
 437 
 438 -- 函数:regexpQuoteMeta(s) 该函数用于在字符串中的某些预定义字符之前添加反斜杠。
 439 -- 预定义字符:'0''\''|''('')''^''$''''[',']''''* ''+''{'''' - ' 440 -- 这个实现与re2 :: RE2 :: QuoteMeta略有不同。它以\0而不是\x00转义零字节,它只转义所需的字符
 441 ---- 简言之,就是不处理转义字符,一般如果没有用的这个函数,都会有转义的情况出现。
 442 SELECT regexpQuoteMeta('\\\\|[]{}+_-=@!~`&^*%$#'); -- \\\\\|\[\]\{}\+_\-=@!~`&\^\*%\$#
 443 SELECT toString('\\\\'); -- \\
 444 
 445 
 446 --九、条件函数
 447 --->>>>>> 条件函数
 448 -- 1. if(cond, then, else)函数:类似于三元操作符。
 449 -- 中文字符使用双引号,英文字符可不使用引号也可使用当引号或双引号,根据具体情况而定。
 450 -- 如果cond != 0则返回then,如果cond = 0则返回else。 cond必须是UInt8类型,then和else必须存在最低的共同类型。
 451 -- 注意:then和else可以是NULL
 452 SELECT
 453 12 > 10 ? 'desc' : 'asc' AS "三元操作符",
 454 if(12 > 10, 'desc' , 'asc') AS "if()函数",
 455 if(12 > 10, NULL, NULL);
 456 -- 2. multiIf(cond_1, then_1, cond_2, then_2...else)
 457 -- 允许您在查询中更紧凑地编写CASE运算符。类似于java中的switch语法(可以接受2n+1个参数)
 458 SELECT multiIf(1,'one',2,'two',3,'three','not this index');-- 关联case条件表达式
 459 
 460 --十、数学函数
 461 --->>>>>> 数学函数
 462 SELECT
 463 1 * e() AS E,
 464 1 * pi() AS PI,
 465 sqrt(25) AS sqrt_25, --接受一个数值类型的参数并返回它的平方根。
 466 cbrt(27) AS cbrt_27, --接受一个数值类型的参数并返回它的立方根。
 467 exp(10), --接受一个数值类型的参数并返回它的指数
 468 exp10(10), --接受一个数值类型的参数并返回它的10的x次幂。
 469 log(10) AS LOG,
 470 log2(10) AS LOG2, --接受一个数值类型的参数并返回它的底2对数。
 471 ln(e()) AS LOG10; --接受一个数值类型的参数并返回它的自然对数
 472 -- 示例:三西格玛准则
 473 SELECT erf(3 / sqrt(2)); -- 0.997
 474 SELECT
 475 sin(90), -- 返回x的三角正弦值。
 476 cos(90), -- 返回x的三角余弦值。
 477 tan(90), -- 返回x的三角正切值
 478 acos(0), -- 返回x的反三角余弦值。
 479 asin(1), -- 返回x的反三角正弦值。
 480 atan(45); -- 返回x的反三角正切值。
 481 -- pow(x, y), power(x, y) 接受x和y两个参数。返回x的y次方。
 482 SELECT
 483 pow(2, 3), -- 2的三次方
 484 pow(3, 2); -- 3的平方
 485 SELECT
 486 intExp2(4), --2^4 接受一个数值类型的参数并返回它的2的x次幂(UInt64)。
 487 intExp10(2);--10^2 接受一个数值类型的参数并返回它的10的x次幂(UInt64)。
 488 
 489 -- 十一、取整函数
 490 --->>>>>> 取整函数
 491 -- 1.向下取整:floor(x[,N])
 492 SELECT
 493 floor(toFloat32(12.08098), 2), -- 12.08
 494 floor(toFloat32(12.2323), 2), -- 12.23
 495 floor(toFloat32(12.89788), -1), -- 10
 496 floor(toFloat32(12.09590), 3), -- 12.095 (注意:如果按照正常的四舍五入,则应该是12.096,为什么呢?)
 497 floor(toFloat32(12.0987), 3),-- 12.098
 498 floor(10, 2); -- 10
 499 -- 2.四舍五入:round(expression [, decimal_places])
 500 -- 如果decimal_places=0,则取整数;
 501 -- 如果>0,则将值舍入小数点右侧;
 502 -- 如果<0,则将小数点左侧的值四舍五入。
 503 SELECT
 504 round(toFloat32(12.1234), 3),
 505 round(toFloat32(12.0025), 3), -- 12.002(注意:为什么不是12.003呢?)
 506 -- round函数只会最多保留三位有效数字
 507 round(toFloat32(12.0025), 4), -- 12.002
 508 round(toFloat32(12.0025002323), 100); -- 12.003
 509 -- 示例:
 510 SELECT
 511 round(toFloat32(10 / 3)), -- 3
 512 round(toFloat32(10 / 3), 2), -- 3.33
 513 round(toFloat32(10.000/3), 3), -- 3.333
 514 round(toFloat32(10.000/3), 6); -- 3.333
 515 -- roundToExp2() 接受一个数字。如果数字小于1,则返回0。否则,它将数字向下舍入到最接近的(整个非负)2的x次幂。
 516 SELECT
 517 roundToExp2(12.0129), -- 8 = 2^3
 518 roundToExp2(toFloat32(0.01)); -- 0.008
 519 -- 3.向上取整:ceil(x[, N]) 或者 ceiling(x[, N])
 520 SELECT
 521 ceil(12.34343, 3), -- 12.344
 522 ceil(toFloat64(12.34343), 3), -- 12.344
 523 ceil(toFloat32(12.34343), 3), -- 12.344
 524 ceil(12.0011, 3); -- 12.002
 525 
 526 
 527 ---十二、数组函数
 528 --->>>>>> 数组函数
 529 -- 1.数组非空判断相关函数(真为1,假为0)
 530 SELECT empty([]), empty([1,2,3]), notEmpty([1,2,3]), notEmpty([]);
 531 -- 2.数组长度 length() 返回数组中的元素个数。 结果类型是UInt64。 该函数也适用于字符串。
 532 SELECT
 533 -- length(), -- 出现异常
 534 -- length([true, false]), -- 异常
 535 -- length([1,2,,4]), --出现异常!
 536 length([]), -- 0
 537 length(['a','b','c']), -- 3
 538 length([1,2,3]); -- 3
 539 -- 3.扩展判断非空的部分函数如下:不接受任何参数并返回适当类型的空数组
 540 SELECT
 541 emptyArrayUInt8(), -- UInt8的空数组
 542 emptyArrayUInt16(),
 543 emptyArrayUInt32(),
 544 emptyArrayUInt64(),
 545 emptyArrayDate(),
 546 emptyArrayDateTime(),
 547 emptyArrayInt8(),
 548 emptyArrayInt16(),
 549 emptyArrayInt32(),
 550 emptyArrayInt64();
 551 -- 接受一个空数组并返回一个仅包含一个默认值元素的数组。(以下是部分示例)
 552 SELECT
 553 emptyArrayToSingle(emptyArrayInt32()), -- 0
 554 emptyArrayToSingle(emptyArrayUInt32()), -- 0
 555 emptyArrayToSingle(emptyArrayDate()), -- 0002-11-30
 556 emptyArrayToSingle(emptyArrayDateTime()); --0002-11-30 08:00:00
 557 -- 4.生成一个含有N个元素的数组,元素从0开始增长,步长尾1.
 558 -- range(N) 返回从0到N-1的数字数组。 以防万一,如果在数据块中创建总长度超过100,000,000个元素的数组,则抛出异常
 559 SELECT
 560 range(10), -- [0,1,2,3,4,5,6,7,8,9]
 561 range(2), -- [0,1]
 562 -- range(5.5), -- 出现异常,N为Int8的数据类型,正整数
 563 -- range(-10), -- 出现异常,DB::Exception: Illegal type Int8 of argument of function range
 564 range(1); -- 0
 565 -- 5.新建一个数组的函数:array(x1,……) 类似于 直接[x1,……]
 566 -- 注意:新建数组的每个元素的数据类型需保持一致性。
 567 SELECT
 568 array(1,2,2,3,4) AS "array()函数",
 569 -- [1,'hello',3], -- 出现异常,DB::Exception: There is no supertype for types UInt8, String, UInt8 because some of them are String/FixedString and some of them are not (version 19.10.1.5 (official build))
 570 [1,2,3,4] AS "[ ]";
 571 -- 6.合并N个数组 arrayConcat(arrays) 合并参数中传递的所有数组。跟java的数组差不多的合并,不会自动去重,不会自动排序
 572 SELECT
 573 arrayConcat(array(1,2),array(2,3),array(4,5)), -- [1,2,2,3,4,5](第一种情况)
 574 arrayConcat(array(1,1),array(2,2),array(3,3)), -- [1,1,2,2,3,3]
 575 -- arrayConcat(array(1,2),['a','c'],array(3,3)), -- 出现异常,不能将不同类型的数组进行合并
 576 arrayConcat(array(1,1),[2,3],array(4,5)); -- [1,1,2,3,4,5]
 577 -- 7.从数组arr中获取索引为“n”的元素。
 578 -- n必须是任何整数类型。 数组中的索引从一开始。 支持负索引。在这种情况下,它选择从末尾开始编号的相应元素。例如,arr [-1]是数组中的最后一项。
 579 -- 如果索引超出数组的边界,则返回默认值(数字为0,字符串为空字符串等).
 580 SELECT
 581 arrayElement(array(10,20,3), 1), -- 10
 582 arrayElement(array(1,20,3), 2), -- 20
 583 arrayElement(array(1,2,30), 3), -- 30
 584 arrayElement(array(10,20,3), 0), -- 0
 585 arrayElement(array(10,20,3), -3), -- 10
 586 arrayElement(array(10,20,3), -2), -- 20
 587 arrayElement(array(10,20,3), -1);-- 3
 588 -- 8.检查在数组中是否含有此元素。has(arr, elem) 包含此元素则返回1,否则返回0
 589 -- has() 检查'arr'数组是否具有'elem'元素。 如果元素不在数组中,则返回0;如果在,则返回1。
 590 -- hasAny(arr1, arr2) 返回1表示arr1和arr2存在交集。否则返回0.
 591 --注意:特殊的定义:
 592 -- ① “NULL”作为数组中的元素值进行处理。
 593 -- ② 忽略两个数组中的元素值的顺序
 594 -- hasAll(set, subset) 检查一个数组是否是另一个数组的子集。返回1,表示set包含subset中所有的元素
 595 -- set – 具有一组元素的任何类型的数组。
 596 -- subset – 任何类型的数组,其元素应该被测试为set的子集。
 597 -- 注意:特殊的定义:
 598 -- ① 空数组是任何数组的子集。
 599 -- ② “NULL”作为数组中的元素值进行处理。
 600 -- ③ 忽略两个数组中的元素值的顺序。
 601 SELECT
 602 has([1,2,3], 2), -- 1
 603 has(array(1,2,3),2), -- 1
 604 has([1,2,NULL], NULL), -- 1 (注意:null值的处理)
 605 -- has([], 2), -- 出现异常,DB::Exception: Types of array and 2nd argument of function has must be identical up to nullability or numeric types or Enum and numeric type. Passed: Array(Nothing) and UInt8
 606 has([1,2], 3); -- 0
 607 SELECT
 608 hasAll([], []), -- 1
 609 hasAll([1,NULL,NULL], [NULL]), -- 1
 610 hasAll([1,2,3], [1,2]), -- 1
 611 hasAll([1,2,2,3], [2]), -- 1
 612 hasAll(array(1,2,2,3), [2]), -- 1
 613 hasAll([1,2,3], [4,5]); -- 0
 614 -- 多重数组(如下的二维数组)。
 615 SELECT hasAll([[1, 2], [3, 4]], [[1, 2], [3, 5]]); -- 0
 616 SELECT
 617 hasAny(array(1,2,3), array(1)), -- 1
 618 hasAny(array(1,2,3), array(1,4,56,80)), -- 1
 619 -- []与array()是一样的含义,本质上是一直的。只不过[]更加简便而已。
 620 hasAny(array(), array()), -- 0
 621 hasAny([],[]), -- 0
 622 hasAny([1],[]), -- 0
 623 -- 空数组跟null不是一样的对象
 624 hasAny([1,NULL],[]), -- 0
 625 hasAny([1,NULL],[NULL,2]); -- 1
 626 
 627 
 628 -- 9.返回数组指定元素的索引
 629 -- indexOf(arr, x) 返回数组中第一个‘x’元素的索引(从1开始),如果‘x’元素不存在在数组中,则返回0。
 630 SELECT indexOf(['one','two','three'], 'one'); -- 1
 631 SELECT indexOf([1, 2, 4], 4); -- 3
 632 SELECT
 633 indexOf(['one','two','three'], 'one'), -- 1
 634 indexOf(['one',NULL,NULL], NULL),-- 1返回第一个找到的元素的索引位置
 635 indexOf([1, 2, 4], 4); -- 3
 636 -- 数组元素的以第一个和最后一个元素。
 637 SELECT length([12,3,4,4,4]);
 638 SELECT array(12,22,31)[1];
 639 
 640 WITH
 641 [23,43,565,2,32,34] AS arr
 642 SELECT
 643 arr[1], -- 去除数组中的第一个元素
 644 arr[length(arr)]; -- 提取元素中的最后一个元素
 645 
 646 -- 10.计算数组中包含指定元素的个数
 647 -- countEqual(arr, x) 返回数组中等于x的元素的个数。相当于arrayCount(elem - > elem = x,arr)。
 648 -- 注意:null值将作为单独的元素值处理。
 649 SELECT
 650 countEqual([1, 2, 2, 2, 3, 4], 2), -- 3
 651 countEqual([1, 2, NULL, NULL], NULL); -- 2
 652 
 653 -- 11.arrayEnumerate(arr) 返回 Array [1, 2, 3, ..., length (arr) ] 此功能通常与ARRAY JOIN一起使用。它允许在应用ARRAY JOIN后为每个数组计算一次。
 654 SELECT arrayEnumerate([1,20,20,3]); -- [1,2,3,4]
 655 SELECT arrayEnumerate(array(11,20,13)); -- [1,2,3]
 656 SELECT arrayEnumerate(array(11,20,13,NULL)); -- [1,2,3,4] 注意:null也算是一个元素。
 657 --arrayEnumerateUniq(arr) 返回与源数组大小相同的数组,其中每个元素表示与其下标对应的源数组元素在源数组中出现的次数
 658 SELECT arrayEnumerateUniq([1,1,2,2]); -- [1,2]
 659 
 660 -- 12.删除数组的元素
 661 -- arrayPopBack(array) 删除数组array的最后一项
 662 SELECT arrayPopBack(array(1,2,3,0)) AS res; -- [1,2,3]
 663 -- arrayPopFront(array) 从数组中删除第一项
 664 SELECT arrayPopFront(array(0,1,2,3)) AS res; -- [1,2,3]
 665 
 666 -- 13.添加数组的元素 arrayPushFront(array, single_value) single_value是单个值
 667 SELECT arrayPushBack([1,2,3], 0) AS res; -- [1,2,3,0]
 668 SELECT arrayPushFront([1,2,3], 0) AS res; -- [0,1,2,3]
 669 
 670 -- 14.更改数组的长度 arrayResize(arr, size[, extender])
 671 -- 如果arr的长度 > size,则会对arr截取size的长度;
 672 -- 如果arr的长度 < size,则其余位置用对应数据类型的默认值填充。
 673 -- 注意:extender含义是扩展元素的值。如果没有指定extender,则默认按照对应的数据类型的默认值进行赋值。否则按照extender进行填充。
 674 SELECT arrayResize([1,2,3], 5); -- [1,2,3,0,0]
 675 SELECT arrayResize([1,2,3], 2); -- [1,2]
 676 SELECT arrayResize([1,2,3], 3); -- [1,2,3]
 677 --↓↓↓ RuntimeException: Parse exception: ByteFragment{[[[1,2],[3,4],[5,6],[],[]]], start=0, len=25}
 678 SELECT arrayResize([array(1,2),array(3,4),array(5,6)], 5);
 679 SELECT arrayResize([1,2,3], 5, 12); -- [1,2,3,12,12]
 680 SELECT arrayResize(['one','two','three'], 5); -- ['one','two','three','','']
 681 SELECT arrayResize(['one','two','three'], 5, 'default'); -- ['one','two','three','default','default']
 682 
 683 -- 15.截取数组的部分元素,得到一个新的子数组
 684 -- arraySlice(array, offset[, length])
 685 -- 解释:
 686 -- array: 数组,
 687 -- offset – 数组的偏移。正值表示左侧的偏移量,负值表示右侧的缩进值。数组下标从1开始。
 688 -- length - 子数组的长度。如果指定负值,则该函数返回[offset,array_length - length。如果省略该值,则该函数返回[offset,the_end_of_array]。
 689 SELECT
 690 arraySlice([1,2,3,4,5,6], 0, 3), -- 无返回值
 691 arraySlice([1,2,NULL,5,6], 1, 3), -- [1,2,0]
 692 arraySlice(['one','two',NULL], 1, 3), -- ['one','two','']
 693 arraySlice([1,2,3,4,5,6], 1, 3); -- [1,2,3]
 694 
 695 -- 16.数组排序:arraySort([func,] arr, ……)
 696 -- 注意:如果在字符串数组中,''和NULL是需要特别对待的,''需要放在最前面,而NULL则是按顺序存放到最后的。
 697 -- arraySort是高阶函数。您可以将lambda函数作为第一个参数传递给它。在这种情况下,排序顺序由lambda函数的调用结果决定。
 698 SELECT
 699 arraySort(['a','',NULL,'c','b']) AS hasNullempty1, --['','a','b','c',''] (第一个是'',最后一个''起始是NULL)
 700 arraySort(array('ac','ab','bc','ad',NULL)) AS hasNull, -- ['ab','ac','ad','bc','']
 701 arraySort(array('ac','','ab',NULL,'bc','ad',NULL)) AS hasNullempty2, -- ['','ab','ac','ad','bc','','']
 702 arraySort([5,4,3,2,1]) AS numSorted,-- [1,2,3,4,5] (数字排序)
 703 arraySort(['ca','bb','ac']) AS strSorted;-- ['ac','bb','ca'] (字符串排序)
 704 SELECT
 705 arraySort([NULL, 1, 3, NULL, 2]) AS sortedArr, -- [1,2,3,0,0]
 706 arrayReverse(sortedArr) AS reverseSortdArr;-- [0,0,3,2,1]
 707 -- 下面这种排序的实质,正数转成负数,再在数学上比较升序排序。
 708 SELECT arraySort(x -> -x, [1,2,3]) as res; -- [3,2,1] 降序:(高阶函数用法)
 709 SELECT arraySort((x) -> -x, [1,2,3]) as res; -- [3,2,1] 降序:(高阶函数用法)
 710 SELECT arraySort(x -> x, [5,4,3,1,2,3]) as res; -- [1,2,3,3,4,5] 升序:(高阶函数用法)
 711 SELECT arraySort((x) -> x, [5,4,3,1,2,3]) as res; -- [1,2,3,3,4,5] 升序:(高阶函数用法)
 712 -- arraySort(lambda, arr1, arr2)
 713 SELECT arraySort((x, y) -> y, ['hello', 'world'], [2, 1]) as res; -- ['world','hello']
 714 SELECT arraySort((x, y) -> -y, [0, 1, 2], [1, 2, 3]) as res; -- [2,1,0]
 715 -- 再次提醒:NULL, NaN, Inf的排序顺序:
 716 -- 含义:
 717 -- -Inf 是数组中的第一个。
 718 -- NULL 是数组中的最后一个。
 719 -- NaN 在NULL的前面。
 720 -- Inf 在NaN的前面。
 721 -- 出现异常:RuntimeException: Parse exception:
 722 -- ByteFragment{[[-inf,-4,1,2,3,inf,nan,nan,NULL,NULL]], start=0, len=37}
 723 SELECT arraySort([1, nan, 2, NULL, 3, nan, -4, NULL, inf, -inf]);
 724 
 725 -- 17.数组翻转:arrayReverse([func,] arr, ……)
 726 -- 如果是NULL的话在排序的过程中,根据数组的数据类型进行默认值填充。
 727 SELECT
 728 arrayReverse(array('a','b','c',NULL)) AS hasOneNull, -- ['','c','b','a']
 729 arrayReverse(array('ac','ab','bc','ad',NULL)) AS hasNull, -- ['','ad','bc','ab','ac']
 730 --网格视图: ['[NULL]','ad','bc','','ab','[NULL]','','ac'];文本视图 :['','ad','bc','','ab','','','ac']
 731 arrayReverse(array('ac','',NULL,'ab','','bc','ad',NULL)) AS hasNullEmpty,
 732 arrayReverse(array(NULL, 3, NULL, 2, 1)),-- [1,2,0,3,0]
 733 arrayReverse([1,2,3,4]);-- [4,3,2,1]
 734 
 735 -- 18.数组排序并翻转:arraySort([func,] arr, ...)
 736 SELECT arrayReverseSort([1, 3, 3, 0]); -- [3,3,1,0]
 737 SELECT arrayReverseSort(['hello', 'world', '!']); -- ['world','hello','!']
 738 --RuntimeException: Parse exception: ByteFragment{[[inf,3,2,1,-4,-inf,nan,nan,NULL,NULL]], start=0, len=37}
 739 SELECT arrayReverseSort([1, nan, 2, NULL, 3, nan, -4, NULL, inf, -inf]) as res;-- [inf,3,2,1,-4,-inf,nan,nan,NULL,NULL]
 740 -- 下面的执行顺序为:
 741 -- 1.首先,根据lambda函数的调用结果对源数组([1, 2, 3])进行排序。 结果是[3, 2, 1]。
 742 -- 2.反转上一步获得的数组。 所以,最终的结果是[1, 2, 3]。
 743 SELECT arrayReverseSort((x) -> -x, [1, 2, 3]) as res; -- [1,2,3]
 744 SELECT arrayReverseSort((x) -> x, [1, 2, 3]) as res; -- [1,2,3]
 745 -- 下面的执行顺序为:
 746 -- 1.首先,根据lambda函数的调用结果对源数组(['hello''world'])进行排序。 其中,在第二个数组([2,1])中定义了源数组中相应元素的排序键。 所以,排序结果['world''hello']。
 747 -- 2.反转上一步骤中获得的排序数组。 所以,最终的结果是['hello''world']。
 748 SELECT arrayReverseSort((x, y) -> y, ['hello', 'world'], [2, 1]) as res;-- ['hello','world']
 749 SELECT arrayReverseSort((x, y) -> -y, ['hello', 'world'], [2, 1]) as res;-- ['world','hello']
 750 SELECT arrayReverseSort((x, y) -> x, ['hello', 'world'], [2, 1]) as res;-- ['world','hello']
 751 --出现异常:Illegal type String of argument
 752 --SELECT arrayReverseSort((x, y) -> -x, ['hello', 'world'], [2, 1]) as res;
 753 SELECT arrayReverseSort((x, y) -> x, ['hello', 'world'], [1, 2]) as res;-- ['world','hello']
 754 
 755 -- 19.统计数组中不重复元素的个数。arrayUniq(arr,……)
 756 -- ① 如果传递一个参数,则计算数组中不同元素的数量。
 757 -- ② 如果传递了多个参数,则它计算多个数组中相应位置的不同元素元组的数量
 758 SELECT
 759 arrayUniq([1,2,3]), -- 3
 760 arrayUniq([1,2,2,2,3]); -- 3
 761 SELECT
 762 arrayUniq([1,2,3],[2,3,4]),
 763 arrayUniq([1,2,2],[1,3,3]);
 764 
 765 -- 20.数组的特殊功能:arrayJoin(arr) 这是一个非常有用的函数。
 766 -- 解释:此函数将数组作为参数,并将该行在结果集中复制数组元素个数
 767 SELECT arrayJoin([1, 2, 3] AS src) AS dst, 'Hello', src;
 768 -- 每个元素扩大两倍;
 769 SELECT arrayJoin([1,2,3]) * 2;
 770 SELECT arrayJoin([-1,-2,0,1,2]) * 2;
 771 --出现异常: Illegal types Array(UInt8) and Array(UInt8) of arguments of function multiply
 772 --SELECT multiply(array(1,2,3), 2);
 773 SELECT multiply(arrayJoin([-1,-2,0,1,2]), 2);
 774 -- 每个元素缩小两倍
 775 SELECT arrayJoin([-4,-2,0,2,4]) / 2;
 776 SELECT divide(arrayJoin([-4,-2,0,2,4]) , 2);
 777 
 778 
 779 -- 21.arrayDifference(arr)
 780 -- 返回一个数组,其中包含所有相邻元素对之间的差值
 781 SELECT arrayDifference([1,2,3,4]);-- [0,1,1,1]
 782 SELECT arrayDifference([1,3,10,50]);-- [0,2,7,40]
 783 
 784 
 785 -- 22. arrayDistinct(arr)返回一个包含所有数组中不同元素的数组.
 786 -- 类似于java的Set集合,对list集合进行去重。
 787 SELECT arrayDistinct(array(1,2,3,4,4,4)); -- [1,2,3,4]
 788 SELECT arrayDistinct([1,2,2,3,4,2,2,5,4,5]); -- [1,2,3,4,5]
 789 SELECT arrayDistinct(array(0,1,NULL,3,4,4,4)); -- [0,1,3,4]
 790 -- 数组去重统计元素个数
 791 SELECT uniq(arrayJoin([1,2,3,6,3])); -- 4 表示数组去重后元素的个数
 792 SELECT uniqArray([1,2,3,4,1,2,3,4]); -- 4 表示数组去重后元素的个数
 793 -- 数组元素累计
 794 SELECT sumArray([1,2,3,4,5]);-- 15
 795 SELECT sum(arraySum([1,2,3,4,5])); -- 15
 796 
 797 
 798 -- 23. arrayEnumerateDense(arr) 返回与源数组大小相同的数组,指示每个元素首次出现在源数组中的位置
 799 SELECT
 800 arrayEnumerateDense([10,20,20,10,30]) AS numArrEnumDense,-- [1,2,2,1,3]
 801 -- [1,1,2,3,4,1,3,5,5]
 802 arrayEnumerateDense([10,10,2,12,3,10,12,NULL,NULL]) as arrEnumDenseHasNull,
 803 -- [1,2,1,1,2,3]
 804 arrayEnumerateDense([10,20,10,10,20,30]) AS arrEnumDese2;
 805 
 806 -- 24. arrayIntersect(arr,……) 返回所有数组元素的交集。
 807 -- 如果arr的数目只有一个,则返回它本身;如果有多个数组,则返回所有数组中元素的交集。
 808 SELECT
 809 -- 注意:最后得到的数组元素的顺序。(有什么影响吗?)
 810 arrayIntersect(['one','two'],['one','two','three']) as uniStrArr1, -- ['two','one']
 811 arrayIntersect(['aaa','bbb'],['bbb','aaa','three']) as uniStrArr2, -- ['bbb','aaa']
 812 arrayIntersect([1,2],[1,2,3]) as uniArr1, -- [1,2]
 813 arrayIntersect([1,2],[1,2,3],[2,3,4],[2,3,4]) as uniArr2; -- 2
 814 SELECT
 815 arrayIntersect([1,2], [3,4]), -- []
 816 arrayIntersect([1,2]);-- [1,2]
 817 
 818 -- 25.arrayReduce(agg_func, arr1, ...)
 819 -- agg_func 为聚合函数,传入到数组当中。
 820 -- 将聚合函数应用于数组并返回其结果.如果聚合函数具有多个参数,则此函数可应用于相同大小的多个数组。
 821 SELECT
 822 arrayReduce('max', [1,2,3]) AS minNum,--最大值 3
 823 arrayReduce('min', [1,2,3]) AS maxNum,--最小值 1
 824 arrayReduce('sum', [1,2,3]) AS sumNum;--求和 6
 825 
 826 -- 十三、 字符串查分合并函数
 827 --->>>>>> 字符串拆分合并函数
 828 -- 1.splitByChar(separator, s) 将字符串以‘separator’拆分成多个子串。
 829 -- ‘separator’必须为仅包含一个字符的字符串常量。 返回拆分后的子串的数组。
 830 -- 如果分隔符出现在字符串的开头或结尾,或者如果有多个连续的分隔符,则将在对应位置填充空的子串。
 831 SELECT splitByChar(',', 'hello,world!'); -- ['hello','world!']
 832 --下面异常:Illegal separator for function splitByChar. Must be exactly one byte.
 833 --SELECT splitByChar('or', 'hello,world!');
 834 
 835 -- 2.splitByString(separator, s)
 836 -- 与上面相同,但它使用多个字符的字符串作为分隔符。 该字符串必须为非空
 837 SELECT splitByString('or','goodorniceorgreat'); -- ['good','nice','great']
 838 
 839 -- 3.alphaTokens(s) 从范围a-z和A-Z中选择连续字节的子字符串。返回子字符串数组
 840 SELECT alphaTokens('abca1abc'); -- ['abca','abc']
 841 SELECT alphaTokens('abc1232abc2wer3rtty'); -- ['abc','abc','wer','rtty']
 842 
 843 -- 4.数组元素合并函数:arrayStringConcat(arr[, sparator])
 844 -- 使用separator将数组中列出的字符串拼接起来。
 845 -- ‘separator’是一个可选参数:一个常量字符串,默认情况下设置为空字符串。 返回拼接后的字符串
 846 SELECT arrayStringConcat([1,2,3], '-'); -- 出现异常,要求数组必须是字符串string类型的元素
 847 SELECT arrayStringConcat(['one','two','three']); -- onetwothree
 848 SELECT arrayStringConcat(['one','two','three'], '-'); -- one-two-three
 849 SELECT arrayStringConcat(['one','two','three',''], '-');-- one-two-three- 注意:NULL不能存在arr中
 850 
 851 
 852 --十四、位操作符
 853 --->>>>>> 位操作符
 854 --位操作函数适用于UInt8,UInt16,UInt32,UInt64,Int8,Int16,Int32,Int64,Float32或Float64中的任何类型。
 855 --结果类型是一个整数,其位数等于其参数的最大位。
 856 --如果至少有一个参数为有符数字,则结果为有符数字。如果参数是浮点数,则将其强制转换为Int64。
 857 SELECT
 858 bitAnd(1,0), -- 0
 859 bitAnd(1,1), -- 1
 860 bitAnd(1,2), -- 0
 861 bitAnd(-1,0), -- 0
 862 bitAnd(-1,-2), -- -2
 863 bitAnd(-10,-1), -- -10
 864 bitOr(1,2), -- 3
 865 bitOr(1,0), -- 1
 866 bitOr(2,0), -- 2
 867 bitOr(0,2); -- 2
 868 SELECT bitXor(1, 2), bitXor(20, 15), bitNot(2);-- 3 27 253
 869 
 870 
 871 --十五、Hash函数:可以用于将元素不可逆的伪随机打乱。
 872 -- 注意:伪随机!
 873 SELECT
 874 -- 计算字符串的MD5值。( 如果您不需要一定使用MD5,请使用‘sipHash64’函数。)
 875 halfMD5('HELLO WORLD!'),
 876 halfMD5(12);
 877 SELECT
 878 MD5('drew-zero,78967');
 879 
 880 SELECT
 881 -- 为任何类型的整数计算32位的哈希。 这是相对高效的非加密Hash函数
 882 intHash32(1221232132132) AS intHash32,
 883 -- 推荐:从任何类型的整数计算64位哈希码。 它的工作速度比intHash32函数快。
 884 intHash64(1221232132132) AS intHash64,
 885 -- 计算任意数量字符串的CityHash64或使用特定实现的Hash函数计算任意数量其他类型的Hash。
 886 cityHash64('username') AS cityHash64,
 887 -- 1.使用sha1或者sha224加密的话,只能用于字符串
 888 -- 2.字符串 需使用单引号。
 889 SHA1('1232131') AS sha1,
 890 SHA224('1232131') AS sha224,
 891 SHA256('DREW-ZERO') AS sha256;
 892 
 893 -- URLHash(url[, N]) 一种快速的非加密哈希函数,用于规范化的从URL获得的字符串
 894 -- 从一个字符串计算一个哈希,如果结尾存在尾随符号/,?或#则忽略。 URLHash(s,N)
 895 -- 计算URL层次结构中字符串到N级别的哈希值,如果末尾存在尾随符号/,?或#则忽略。 URL的层级与URLHierarchy中的层级相同
 896 -- 用处:此函数被用于Yandex.Metrica。
 897 SELECT
 898 URLHash('www.baidu.com'), -- 11390370829909720855
 899 URLHash('www.baidu.com', 0), -- 11390370829909720855
 900 -- 
 901 URLHash('www.baidu.com', 1); -- 11160318154034397263
 902 
 903 -- farmHash64(s) 计算字符串的FarmHash64。 接受一个String类型的参数。返回UInt64。
 904 SELECT farmHash64('www.runoob.com'); -- 6668483584160323388
 905 
 906 -- javaHash(s) 计算字符串的JavaHash。 接受一个String类型的参数。返回Int32。
 907 SELECT javaHash('www.baidu.com'); -- 270263191
 908 
 909 -- hiveHash(s) 计算字符串的HiveHash。 接受一个String类型的参数。返回Int32。 与JavaHash相同,但不会返回负数
 910 SELECT hiveHash('www.baidu.com'); -- 270263191
 911 
 912 
 913 --十六、随机函数
 914 --->>>>>> 随机函数
 915 -- 解释:随机函数使用非加密方式生成【伪随机】数字。
 916 -- ① 所有随机函数都只接受一个参数或不接受任何参数。
 917 -- ② 您可以向它传递任何类型的参数,但传递的参数将不会使用在任何随机数生成过程中。
 918 -- ③ 此参数的唯一目的是防止公共子表达式消除,以便在相同的查询中使用相同的随机函数生成不同的随机数
 919 -- rand() 函数:返回一个UInt32类型的随机数字,所有UInt32类型的数字被生成的概率均相等。
 920 -- rand64() 函数:返回一个UInt64类型的随机数字,所有UInt64类型的数字被生成的概率均相等。
 921 -- randConstant() 函数:返回一个UInt32类型的随机数字,该函数不同之处在于仅为每个数据块参数一个随机数。
 922 SELECT
 923 rand(), -- 1751687411
 924 rand(10), -- 1124981728
 925 rand64(),
 926 rand64(10),
 927 randConstant(),
 928 randConstant();
 929 
 930 
 931 -- 十七、编码函数:
 932 -- hex(), unhex(), UUIDStringToNum(str), UUIDNumToString(str),bitmaskToList(num) ...
 933 -- 1.hex函数编码
 934 SELECT
 935 -- 68656C6C6F20776F726C64212C68656C6C6F20636C69636B686F757365
 936 hex('hello world!,hello clickhouse') AS hexStr,
 937 hex(now()) AS hexDatetime, -- 5D414BA2
 938 hex(toDate(now())) AS hexDate; --46BC
 939 
 940 -- 2.接受包含36个字符的字符串,格式为“123e4567-e89b-12d3-a456-426655440000”,并将其转化为FixedString(16)返回
 941 SELECT UUIDStringToNum('123e4567-e89b-12d3-a456-426655440000');
 942 
 943 -- 3. 接受一个整数。返回一个UInt64类型数组,其中包含一组2的幂列表,其列表中的所有值相加等于这个整数。数组中的数字按升序排列。
 944 -- bitmaskToArray(num)
 945 SELECT bitmaskToArray(10); -- [2,8]
 946 SELECT bitmaskToArray(100); -- [4,32,64]
 947 
 948 -- 4.接受一个整数。返回一个字符串,其中包含一组2的幂列表,其列表中的所有值相加等于这个整数。列表使用逗号分割,按升序排列。
 949 -- bitmaskToList(num)
 950 SELECT bitmaskToList(10); -- 2,8
 951 SELECT bitmaskToList(100); -- 4,32,64
 952 SELECT bitmaskToList(0); -- '' 空字符串
 953 
 954 
 955 --十八、UUID函数
 956 --->>>>>> UUID函数
 957 -- 1.generateUUIDv4() 返回 UUID类型的值。
 958 SELECT generateUUIDv4() as randomUUID; -- 随机生成一个UUIDv4的字符串(b6940dfe-0dc9-4788-bac7-319d13235a2e)
 959 SELECT replaceAll(toString(generateUUIDv4()), '-', '') AS replaceUUID; -- 9d1947ea4fcf450da5391feb6142cab6
 960 
 961 -- 2.toUUID(s) 将string类型的值 转换成UUID类型的值
 962 SELECT toUUID('61f0c404-5cb3-11e7-907b-a6006ad3dba0') AS uuid;
 963 
 964 -- 3.接受一个String类型的值,其中包含36个字符且格式为xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx,
 965 -- 将其转换为UUID的数值并以FixedString(16)将其返回。
 966 SELECT
 967 '612f3c40-5d3b-217e-707b-6a546a3d7b29' AS uuid, -- 612f3c40-5d3b-217e-707b-6a546a3d7b29
 968 UUIDStringToNum(uuid) AS bytes; --a/<@];!~p{jTj={)
 969 
 970 -- 4. UUIDNumToString() 接受一个FixedString(16)类型的值,返回其对应的String表现形式。
 971 SELECT 'a/<@];!~p{jTj={)' AS bytes,
 972 UUIDNumToString(toFixedString(bytes, 16)) AS uuid;
 973 
 974 --- 二十、 URL函数:所有这些功能都不遵循RFC。它们被最大程度简化以提高性能。
 975 --- 什么事RFC?
 976 ---- Request For Comments(RFC),是一系列以编号排定的文件。文件收集了有关互联网相关信息,以及UNIX和互联网社区的软件文件。
 977 -- 1. 截取函数:如果URL中没有要截取的内容则返回空字符串。
 978 SELECT protocol('http://www.baidu.com');-- http
 979 SELECT protocol('https://www.baidu.com');-- https
 980 SELECT protocol('www.baidu.com');-- ''
 981 -- 获取域名。
 982 SELECT domain('http://www.baidu.com'); -- www.baidu.com
 983 SELECT domain('https://www.google.com.cn'); -- www.google.com.cn
 984 -- 返回域名并删除第一个‘www.’
 985 SELECT domainWithoutWWW('http://www.baidu.com');-- baidu.com
 986 SELECT domainWithoutWWW('www.baidu.com');-- ''
 987 -- 返回顶级域名。例如:.ru
 988 SELECT topLevelDomain('http://www.runoob.com.cn'); -- cn
 989 SELECT topLevelDomain('https://www.huse.edn'); -- edu
 990 -- 返回“第一个有效子域名”
 991 -- 如果顶级域名为‘com’,‘net’,‘org’或者‘co’则第一个有效子域名为二级域名。否则则返回三级域名
 992 SELECT firstSignificantSubdomain('https://news.yandex.com.tr/'); -- yandex
 993 -- 返回包含顶级域名与第一个有效子域名之间的内容(参阅上面内容)
 994 SELECT cutToFirstSignificantSubdomain('https://news.yandex.com.tr/'); -- yandex.com.tr
 995 -- 返回URL路径
 996 SELECT path('https://blog.csdn.net/u012111465/article/details/85250030');-- /u012111465/article/details/85250030
 997 -- 与上面相同,但包括请求参数和fragment。
 998 SELECT pathFull('https://clickhouse.yandex/#quick-start'); -- /#quick-start
 999 -- 返回请求参数。例如:page=1&lr=213。请求参数不包含问号已经# 以及# 之后所有的内容。
1000 SELECT queryString('http://www.baidu.com/?page=1&lr=234'); -- page=1&lr=234 (根据?确定)
1001 SELECT queryString('http://www.baidu.com/page=1&lr=234'); -- ''
1002 -- 返回URL的fragment标识。fragment不包含#。
1003 SELECT fragment('https://clickhouse.yandex/#quick-start'); -- quick-start
1004 -- 返回请求参数和fragment标识。例如:page=1#29390。
1005 SELECT queryStringAndFragment('https://www.baidu.com/s?ie=utf-8&rsv_sug7=100#ei-ai'); -- ie=utf-8&rsv_sug7=100#ei-ai
1006 
1007 
1008 -- 2. 删除URL中的部分内容 (如果URL中不包含指定的部分,则URL不变。)
1009 SELECT cutWWW('www.baidu.com');-- www.baidu.com
1010 SELECT cutWWW('https://www.baidu.com');-- www.baidu.com
1011 SELECT cutWWW('https://www.baidu.com');-- www.baidu.com
1012 -- 删除请求参数
1013 SELECT cutQueryString('http://www.baidu.com/1?page=1'); -- http://www.baidu.com/1
1014 -- 删除fragment标识。#同样也会被删除。
1015 SELECT cutFragment('http://www.baidu.com/#quick-demo'); -- http://www.baidu.com/
1016 -- 删除请求参数以及fragment标识。问号以及#也会被删除。
1017 SELECT cutQueryStringAndFragment('http://www.baidu.com/1?page=23#we'); -- http://www.baidu.com/1
1018 -- cutURLParameter(URL, name) 删除URL中名称为‘name’的参数。下面例子中的参数是:&之后,resv,name
1019 SELECT cutURLParameter('http://www.baidu.com/1?page=1#erre&resv=23&name=user','resv');
1020 
1021 
1022 --二十一、IP函数
1023 
1024  
1025 
1026 --二十二、条件函数
1027 SELECT IF(12 > 10 , 12, 20);
1028 SELECT 12 > 10 ? 12 : 10;
1029 SELECT if(greater(12, 10), 12, 10);
1030 
1031  
1032 
1033 --二十三、操作符函数替换
1034 -- clickhouse自带的计算操作符函数(对接mybatis的时候不用将“<”之类的符号转换成 “age1 <![CDATA[ < ]] 2>”)
1035 -- 1.等于(注意函数名称的大小,严格区分大小写)
1036 SELECT
1037 equals('hello','hello'), -- 1
1038 equals('ab','ba'); -- 0
1039 -- 2.不等于
1040 SELECT
1041 notEquals('a','b'), -- 1
1042 notEquals('a','a'), -- 0
1043 notEquals(12, 12), -- 1
1044 notEquals(12, 1010); -- 0
1045 -- 3.大于( 如果前者大于后者,则返回1;否则返回0)
1046 SELECT
1047 greater(12, 10), -- 1
1048 greater(10, 12), -- 0
1049 greater(12, 12), -- 0
1050 greater('b','a'), -- 1
1051 greater('a','b'); -- 0
1052 -- 3.1 扩展:提取两者中最大的值
1053 SELECT greatest(12,11); -- 12
1054 -- 4.小于(如果前者小于后者,则返回1;否则返回0)
1055 SELECT less(12,23); -- 1
1056 SELECT less(120,23); -- 0
1057 -- 5.大于或等于
1058 SELECT greaterOrEquals(12,12); -- 1
1059 SELECT greaterOrEquals(120,12); -- 1
1060 -- 6.小于或等于
1061 SELECT lessOrEquals(12,12); -- 1
1062 SELECT lessOrEquals(12,129); -- 1
1063 -- ===== String操作
1064 -- *. a LIKE s
1065 SELECT like('a', 'abcd'); -- 0
1066 SELECT like('a', 'a'); -- 1

 

 

 

posted on 2021-03-16 22:13  大鹏的鸿鹄之志  阅读(16184)  评论(0编辑  收藏  举报