-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustom_sort.sql
More file actions
68 lines (48 loc) · 1.77 KB
/
Custom_sort.sql
File metadata and controls
68 lines (48 loc) · 1.77 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
60
61
62
63
64
65
use Practice
---Data table
create table Happiness_index(
Rank int,
Country varchar(50),
Happiness_2021 NUMERIC(3,2),
Happiness_2022 NUMERIC(3,2),
Popultion NUMERIC(15));
--custom sort, order Sweden first
select * ,
CASE when country = 'Sweden' then '1'
else '2'
End as cntry_pr
from Happiness_index
order by cntry_pr,Rank asc
-- calculating running cost
-- creates wrong running cost when same amount exists for multiple records
select *,
sum(amount) over(order by amount asc) as cum_cum
from transactions
-- to solve above, use another col in order or unbounded
select *,
sum(amount) over(order by amount asc rows between unbounded preceding and current row) as cum_sum
from transactions
------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
select * from int_orders
-- Calculate the sum of amount by sales id (grouping by sales id)
select *,
sum(amount) over(partition by salesperson_id)
from int_orders
-- calculate the rolling sum/ cum sum of amount
select *,
sum(amount) over(order by salesperson_id)
from int_orders
-- calculate the rolling sum by considering above 2 records only
select *,
sum(amount) over(order by order_date rows between 2 preceding and current row) as cumsum_2
from int_orders
--- Calculating the cumsum/rolling sum for each sales id
select *,
sum(amount) over(partition by salesperson_id order by order_date)
from int_orders
-- creating lead and lag col
select *,
sum(amount) over(order by salesperson_id rows between 1 preceding and 1 preceding) as lag,
sum(amount) over(order by salesperson_id rows between 1 following and 1 following) as lead
from int_orders