Skip to content

Instantly share code, notes, and snippets.

@filimonov
Created July 4, 2018 10:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save filimonov/2ff5f083c2f874eceebde8877721afc4 to your computer and use it in GitHub Desktop.
Save filimonov/2ff5f083c2f874eceebde8877721afc4 to your computer and use it in GitHub Desktop.
clickhouse runningDifference inside groups
DROP TABLE IF EXISTS test;
CREATE TABLE test (sessionid String, timestamp DateTime) ENGINE = Log;
INSERT INTO test SELECT 's1', arrayJoin([now(), now() + 10, now() + 21, now() + 33]);
INSERT INTO test SELECT 's2', arrayJoin([now()+33, now() + 34, now() + 35, now() + 36]);
INSERT INTO test SELECT 's3', arrayJoin([now()+40, now() + 60, now() + 61, now() + 80]);
WITH
groupArray( timestamp ) as all_timestamps_in_group,
arrayEnumerate( all_timestamps_in_group ) as all_timestamps_in_group_ids,
arrayMap( i -> i > 1 ? all_timestamps_in_group[i] - all_timestamps_in_group[i - 1] : 0, all_timestamps_in_group_ids) as timestamp_diff
SELECT
sessionid,
timestamp_diff
FROM test
GROUP BY sessionid;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment