-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathwith_group_lvl_pivot_data.sql
More file actions
60 lines (50 loc) · 1.91 KB
/
with_group_lvl_pivot_data.sql
File metadata and controls
60 lines (50 loc) · 1.91 KB
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
Исходные данные ниже. Задача представить записи в одной строке если у них разные уровни группировки, т.е
Результат работы запроса ниже :
id summ lvl_group
1 200 1
2 350 1
3 200 1
4 500 2
5 700 2
Т.к. ntile(2) у нас 2, то требуется выводить следующие столбцы id1 summ1 lvl_group1 id2 summ2 lvl_group2
В результате должно получиться следующее :
id1 summ1 lvl_group1 id2 summ2 lvl_group2
1 200 1 4 500 2
2 350 1 5 700 2
3 200 1
with a as (select 1 id, 200 summ from dual union all
select 2 id, 350 summ from dual union all
select 3 id, 200 summ from dual union all
select 4 id, 500 summ from dual union all
select 5 id, 700 summ from dual )
select sub.*
from
(select id,summ,ntile(2) over (order by id) lvl
from a) sub
Решение:
with a as (select 1 id, 200 summ from dual union all
select 2 id, 350 summ from dual union all
select 3 id, 200 summ from dual union all
select 4 id, 500 summ from dual union all
select 5 id, 700 summ from dual )
select sub1.*,sub2.*
from (select row_number() over (partition by lvl order by id) rw
, id
, summ
, lvl
from (select id
, summ
, ntile(2) over (order by id) lvl
from a
) sub
where lvl=1) sub1
left join (select row_number() over (partition by lvl order by id) rw
, id
, summ
, lvl
from (select id
, summ
, ntile(2) over (order by id) lvl
from a
) sub
where lvl=2) sub2 on sub2.rw = sub1.rw