function same as lag partition by in clickouse

China☆狼群 提交于 2020-12-15 06:21:08

问题


I need to know the frequency of order for each user. I mean difference between 2 order time for each user. In SQL I used "Lag Partition by" but I don't know how I can calculate this in click house. I need this data:

at first I should sort data with user_id and created_at then I need to have next order time for each user id in row. I can't use neighbor function because it can't do partition by user_id.


回答1:


I didn't understand why neighbor cannot be used in your case, but it should works well:

SELECT 
    user_id,
    created,
    if(neighbor(user_id, 1, NULL) != user_id, NULL, neighbor(created, 1, NULL)) AS next_created
FROM 
(
    SELECT 
        number % 3 AS user_id,
        now() + (number * 360) AS created
    FROM numbers(11)
    ORDER BY 
        user_id ASC,
        created ASC
)

/*
┌─user_id─┬─────────────created─┬────────next_created─┐
│       0 │ 2020-10-21 16:00:21 │ 2020-10-21 16:18:21 │
│       0 │ 2020-10-21 16:18:21 │ 2020-10-21 16:36:21 │
│       0 │ 2020-10-21 16:36:21 │ 2020-10-21 16:54:21 │
│       0 │ 2020-10-21 16:54:21 │                ᴺᵁᴸᴸ │
│       1 │ 2020-10-21 16:06:21 │ 2020-10-21 16:24:21 │
│       1 │ 2020-10-21 16:24:21 │ 2020-10-21 16:42:21 │
│       1 │ 2020-10-21 16:42:21 │ 2020-10-21 17:00:21 │
│       1 │ 2020-10-21 17:00:21 │                ᴺᵁᴸᴸ │
│       2 │ 2020-10-21 16:12:21 │ 2020-10-21 16:30:21 │
│       2 │ 2020-10-21 16:30:21 │ 2020-10-21 16:48:21 │
│       2 │ 2020-10-21 16:48:21 │                ᴺᵁᴸᴸ │
└─────────┴─────────────────────┴─────────────────────┘
*/



回答2:


groupArray allows to transform this

select 1 uid, 555 time union all select 1, 666 union all select 1, 777
┌─uid─┬─time─┐
│   1 │  555 │
│   1 │  666 │
│   1 │  777 │
└─────┴──────┘

to this

select uid, groupArray(time) dtime from 
   (select * from (select 1 uid, 555 time union all select 1, 666 union all select 1, 777) order by uid, time) 
  group by uid

┌─uid─┬─dtime─────────┐
│   1 │ [555,666,777] │
└─────┴───────────────┘

and

select uid, arrayJoin(arrayPushBack(arrayPopFront(groupArray(time)), null)) dtime from 
   (select * from (select 1 uid, 555 time union all select 1, 666 union all select 1, 777) order by uid, time) 
  group by uid
┌─uid─┬─dtime─┐
│   1 │   666 │
│   1 │   777 │
│   1 │  ᴺᵁᴸᴸ │
└─────┴───────┘


select uid, time, atime from (
  select uid, groupArray(time) as stime, arrayPushBack(arrayPopFront(stime), null) dtime from 
   (select * from (select 1 uid, 555 time union all select 1, 666 union all select 1, 777) order by uid, time) 
  group by uid )
   array join stime as time, dtime as atime
┌─uid─┬─time─┬─atime─┐
│   1 │  555 │   666 │
│   1 │  666 │   777 │
│   1 │  777 │  ᴺᵁᴸᴸ │
└─────┴──────┴───────┘


来源:https://stackoverflow.com/questions/64466901/function-same-as-lag-partition-by-in-clickouse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!