1. 程式人生 > 其它 >clickhouse案例 連續N天登入

clickhouse案例 連續N天登入

技術標籤:clickhouse

資料

a,2017-02-05,200
a,2017-02-06,300
a,2017-02-07,200
a,2017-02-08,400
a,2017-02-10,600
b,2017-02-05,200
b,2017-02-06,300
b,2017-02-08,200
b,2017-02-09,400
b,2017-02-10,600
c,2017-01-31,200
c,2017-02-01,300
c,2017-02-02,200
c,2017-02-03,400
c,2017-02-10,600
a,2017-03-01,200
a,2017-03-02,300
a,2017-03-03,200
a,2017-03-04,400
a,2017-03-05,600

建表,匯入資料

create table shop(
name String,
ctime Date, cost Float64 ) engine=MergeTree primary key (name,ctime) order by (name,ctime); cat shop.csv | clickhouse-client -q 'insert into shop FORMAT CSV';
select 
name,groupArray(ctime) arr,
arrayEnumerate(arr)  arr_index
from 
shop
group by name
┌─name─┬─arr─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┬─arr_index──────────────┐
│ b    │ [
'2017-02-05','2017-02-06','2017-02-08','2017-02-09','2017-02-10'][1,2,3,4,5] │ │ c │ ['2017-01-31','2017-02-01','2017-02-02','2017-02-03','2017-02-10'][1,2,3,4,5] │ │ a │ [
'2017-02-05','2017-02-06','2017-02-07','2017-02-08','2017-02-10','2017-03-01','2017-03-02','2017-03-03','2017-03-04','2017-03-05'][1,2,3,4,5,6,7,8,9,10] │ └──────┴─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┴────────────────────────┘
select
name,ct,idx,
subtractDays(ct,idx) diff  --日期減去天數
from
	(select 
	name,groupArray(ctime) arr,
	arrayEnumerate(arr)  arr_index
	from 
	shop
	group by name)
array join arr as ct,
arr_index as idx  --在登入日期後面生成連續的數字
┌─name─┬─────────ct─┬─idx─┬───────diff─┐
│ b    │ 2017-02-0512017-02-04 │
│ b    │ 2017-02-0622017-02-04 │
│ b    │ 2017-02-0832017-02-05 │
│ b    │ 2017-02-0942017-02-05 │
│ b    │ 2017-02-1052017-02-05 │
│ c    │ 2017-01-3112017-01-30 │
│ c    │ 2017-02-0122017-01-30 │
│ c    │ 2017-02-0232017-01-30 │
│ c    │ 2017-02-0342017-01-30 │
│ c    │ 2017-02-1052017-02-05 │
│ a    │ 2017-02-0512017-02-04 │
│ a    │ 2017-02-0622017-02-04 │
│ a    │ 2017-02-0732017-02-04 │
│ a    │ 2017-02-0842017-02-04 │
│ a    │ 2017-02-1052017-02-05 │
│ a    │ 2017-03-0162017-02-23 │
│ a    │ 2017-03-0272017-02-23 │
│ a    │ 2017-03-0382017-02-23 │
│ a    │ 2017-03-0492017-02-23 │
│ a    │ 2017-03-05102017-02-23 │
└──────┴────────────┴─────┴────────────┘
select
name,count(1) days
from
	(select
	name,ct,idx,
	subtractDays(ct,idx) diff
	from
		(select 
		name,groupArray(ctime) arr,
		arrayEnumerate(arr)  arr_index
		from 
		shop
		group by name)
	array join arr as ct,
	arr_index as idx)
group by name,diff
order by name,days desc
limit 1 by name;

┌─name─┬─days─┐
│ a    │    5 │
│ b    │    3 │
│ c    │    4 │
└──────┴──────┘