1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
def get_kind_by_priority(model, start, end):
aggregated_data_query = get_where_by_timestamp(model.select(model.order_id,
model.kind,
fn.count(model.kind).alias('_count')
).where(
model.kind != ''
).group_by(
model.order_id,
model.kind
),
model, start, end)
aggregated_data = model.select(
aggregated_data_query.c.order_id,
fn.jsonb_agg(fn.jsonb_build_object(
'kind', aggregated_data_query.c.kind,
'count', aggregated_data_query.c._count
)).alias('kinds')
).from_(aggregated_data_query).group_by(aggregated_data_query.c.order_id).cte('aggregated_data')
filtered_data = (
model.select(
aggregated_data.c.order_id,
SQL("kind_obj->>'kind'").alias('kind'),
SQL("kind_obj->>'count'").cast('int').alias('count')
).from_(
aggregated_data,
fn.jsonb_array_elements(aggregated_data.c.kinds).alias('kind_obj')
).where(fn.jsonb_array_length(aggregated_data.c.kinds) == 1)
.union_all(
model.select(
aggregated_data.c.order_id,
SQL("kind_obj->>'kind'").alias('kind'),
SQL("kind_obj->>'count'").cast('int').alias('count')
).from_(
aggregated_data,
fn.jsonb_array_elements(aggregated_data.c.kinds).alias('kind_obj')
).where(
(fn.jsonb_array_length(aggregated_data.c.kinds) > 1) &
(SQL("kind_obj->>'kind'") != 'default')
)
)
).cte('filtered_data')
ranked_data = (
model.select(
filtered_data.c.order_id,
filtered_data.c.kind,
filtered_data.c.count,
fn.row_number().over(partition_by=[filtered_data.c.order_id], order_by=[filtered_data.c.count.desc()]).alias('rn')
).from_(filtered_data)
)
final_query = (
model.select(
ranked_data.c.order_id,
ranked_data.c.kind
).from_(ranked_data).with_cte(aggregated_data, filtered_data).where(ranked_data.c.rn == 1)
)
return final_query
|