-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSQL_Code.sql
More file actions
6840 lines (5386 loc) · 165 KB
/
SQL_Code.sql
File metadata and controls
6840 lines (5386 loc) · 165 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
69, 86, 87, 41, 54, 57, 58, 65, 66, 67, 119, 113,110, 106, 105, 124
1)
# Get the earliest login date for a user
# Then for each such first (or earliest) login date, find the number of total
users who logged within 90 days prior to this earliest login date
https://leetcode.com/problems/new-users-daily-count/description/
1107. New Users Daily Count
With CTE1 As
(
Select user_id,
min(activity_date) as login_date
From Traffic
Where activity = 'login'
Group By user_id
Order By user_id asc
)
Select login_date,
count(user_id) as user_count
From CTE1
Where login_date
between
DATE_SUB('2019-06-30', INTERVAL 90 DAY) and '2019-06-30'
Group By login_date
2)
2020. Number of Accounts That Did Not Stream
https://leetcode.com/problems/number-of-accounts-that-did-not-stream/description/
Select count(sub.account_id) as accounts_count
From Subscriptions sub
Left Join Streams str
On sub.account_id = str.account_id
Where YEAR(sub.start_date) <= '2021' #had an active subscription in 2021 (bought before or in 2021)
and YEAR(sub.end_date) >= '2021'
and YEAR(str.stream_date) <> '2021'
3)
2066. Account Balance
https://leetcode.com/problems/account-balance/description/
With cte as
(
Select
account_id,
day,
type,
CASE
When type = 'Deposit' Then amount
When type = 'Withdraw' Then -1 * amount
END amount#,
#row_number() Over() as row_num
From Transactions
Order by day asc
)
Select
account_id,
day,
sum(amount) over(Partition By account_id Order By day asc) as balance
From CTE
Group By account_id, day # this is redundant
4)
1709. Biggest Window Between Visits
https://leetcode.com/problems/biggest-window-between-visits/description/
With CTE1 as
(
Select user_id,
visit_date,
dense_rank() over(Partition By user_id Order By visit_date desc) dr
From
(
Select distinct user_id,
'2021-1-1' as visit_date
From UserVisits
Union
Select user_id,
visit_date
From UserVisits
) x
Order By user_id asc, visit_date desc
)
Select a.user_id,
max(DATEDIFF(a.visit_date, b.visit_date)) as biggest_window
From CTE1 a
Inner Join CTE1 b
On b.dr = a.dr + 1
Where a.user_id = b.user_id
Group By a.user_id
5)
https://leetcode.com/problems/evaluate-boolean-expression/description/
1440. Evaluate Boolean Expression
SELECT
*
/*E.*,
CASE E.operator
WHEN ">" THEN IF(V1.value > V2.value, "true", "false")
WHEN "=" THEN IF(V1.value = V2.value, "true", "false")
WHEN "<" THEN IF(V1.value < V2.value, "true", "false")
END AS value */
FROM Expressions E
Inner JOIN Variables V1
ON E.left_operand=V1.name and
E.right_operand = V1.name
6)
https://leetcode.com/problems/product-sales-analysis-iv/description/
2324. Product Sales Analysis IV
With CTE as
(
Select
s.user_id,
s.product_id,
sum(s.quantity * p.price) as 'total_spent'
From Sales s
Inner Join Product p
On s.product_id = p.product_id
Group By s.user_id, s.product_id
Order By user_id asc, total_spent desc #no need to order
),
CTE_1 as
(
Select user_id,
product_id,
total_spent,
dense_rank() over(order by total_spent desc) as rnum
From CTE
)
Select x.user_id,
x.product_id
From CTE_1 x
Inner Join
(
Select user_id,
min(rnum) as r_num
From CTE_1
Group By user_id
) y
On x.user_id = y.user_id and
x.rnum = y.r_num
With CTE as
(
Select
s.user_id,
s.product_id,
sum(s.quantity * p.price) as 'total_spent'
From Sales s
Inner Join Product p
On s.product_id = p.product_id
Group By s.user_id, s.product_id
Order By user_id asc, total_spent desc
),
CTE_1 as
(
Select user_id,
product_id,
total_spent,
dense_rank() over(order by total_spent desc) as rnum
From CTE
)
Select x.user_id,
x.product_id
From CTE x
Inner Join (
Select user_id,
max(total_spent) as max_spent
From CTE
Group By user_id
) y
On x.user_id = y.user_id and x.total_spent = y.max_spent
7)
https://leetcode.com/problems/tree-node/description/
608. Tree Node
Select N,
Type
From
(
# Root has NULL parent
Select N,
'Root' as Type
From Tree
Where P is null
Union
# Inner shows up in both nodes
Select N, 'Inner' as Type
From Tree
Where N in (Select P From Tree) and
P is not null # an inner node will not have a null parent
# Leaf does not show up in parent
#1,3,6
Union
Select N,
'Leaf' as Type
From Tree
Where N not in
(
Select N
From Tree
Where N in (Select P from Tree) # a leaf not is not a parent
)
and P is not null
) x
Order By x.N asc
8)
https://leetcode.com/problems/game-play-analysis-iii/description/
534. Game Play Analysis III
Query 1:
========
Select player_id,
event_date,
sum(games_played) Over (partition by player_id Order By event_date) games_played_so_far
From Activity
Query 2:
SELECT player_id,
event_date,
SUM(games_played) AS total_games_played
FROM Activity
GROUP BY player_id, event_date
ORDER BY player_id, event_date;
'''
Difference Between the Two Approaches:
Cumulative Total:
Window Function: It computes a cumulative total across rows, which accumulates over time.
GROUP BY: It does not compute a cumulative sum. It just gives the sum for each player_id and event_date separately.
Row-Level Calculation:
Window Function: The calculation is done at the row level, and the result is based on all the previous rows (within the partition) up to the current row.
GROUP BY: The calculation happens per group, so each group will just be summed independently without the cumulative effect.
'''
/*
Wrong approach:
In most standard SQL implementations, the ORDER BY clause within a subquery that is used in the SELECT list (and is not a window function) does not guarantee the order in which the rows are processed by the aggregate function (SUM() in this case). The ORDER BY in such a subquery is mainly relevant if you are using functions like LIMIT or if the database optimizer happens to use the order for some internal optimization (which is not guaranteed to affect the final aggregated sum).
To achieve a running total from the latest date backwards, you would need to rethink the subquery logic or use a window function with a different ordering.
Select a.player_id,
a.event_date,
(
Select ifnull(sum(b.games_played),0)
From Activity b
Where b.player_id = a.player_id and a.event_date <= b.event_date
Group By b.player_id
) as games_played_so_far
From Activity a
Group By a.player_id, a.event_date
Order By a.player_id asc,a.event_date desc
*/
9)
1285. Find the Start and End Number of Continuous Ranges
https://leetcode.com/problems/find-the-start-and-end-number-of-continuous-ranges/description/
# Find the Start and End Number of Continuous Ranges
# row_number(), rank(), dense_rank()
Select min(log_id) as start_id,
max(log_id) as end_id
From
(
Select log_id,
rank() Over(Order By log_id) as den_rank,
log_id - (rank() Over(Order By log_id)) diff
From Logs
) x
Group By x.diff
Order By start_id asc
10)
1270. All People Report to the Given Manager
https://leetcode.com/problems/all-people-report-to-the-given-manager/description/
######################### Option 1 ######################
With CTE1 as
(
Select employee_id #direct 2, 77
From Employees
where manager_id = 1 and
employee_id <> 1
),
#2
CTE2 as
(
Select e1.employee_id
From Employees e1
Inner Join Employees e2
On e1.manager_id = e2.employee_id
Where e2.employee_id <> 1 and
e2.manager_id = 1
),
CTE3 as
(
Select e1.employee_id
From Employees e1
Inner Join CTE2 as c
On e1.manager_id = c.employee_id
)
Select employee_id
From CTE1
Union
Select employee_id
From CTE2
Union
Select employee_id
From CTE3
/*
######################### Option 2 ######################
Select e3.employee_id
From
(
Select e2.employee_id
From
(
Select employee_id
From Employees
Where manager_id = 1
) x
Inner Join Employees e2
On x.employee_id = e2.manager_id
) y
Inner Join Employees e3
On y.employee_id = e3.manager_id
Where e3.employee_id <> 1
*/
/*
######################### Option 3 ######################
With CTE1 AS
(
Select employee_id # (1, 2, 77)
From Employees
Where manager_id = 1
),
CTE2 AS
(
Select e.employee_id # (4)
From CTE1 c
Inner Join Employees e
Where e.manager_id = c.employee_id
),
CTE3 AS
(
Select e.employee_id # (4)
From CTE2 c
Inner Join Employees e
Where e.manager_id = c.employee_id
)
Select *
From CTE3
Where employee_id <> 1
*/
11)
# https://leetcode.com/problems/employee-bonus/description/
577. Employee Bonus
Select e.name,
b.bonus
From Employee e
Left Join Bonus b
On e.empId = b.empId
Where COALESCE(b.bonus, 0 ) < 1000
12)
https://leetcode.com/problems/rising-temperature/description/
197. Rising Temperature
Select w2.id
From Weather w1, Weather w2
Where w2.temperature > w1.temperature and
#w2.recordDate > w1.recordDate and
DATEDIFF(w2.recordDate, w1.recordDate) = 1
Select w2.id
From Weather w1
Inner Join Weather w2
On w2.recordDate = w1.recordDate + 1
Where w2.temperature > w1.temperature
13)
#https://leetcode.com/problems/customer-who-visited-but-did-not-make-any-transactions/description/
1581. Customer Who Visited but Did Not Make Any Transactions
Select customer_id,
SUM(IF(t.transaction_id is null, 1, 0)) as count_no_trans
From Visits v
Left Join Transactions t
On v.visit_id = t.visit_id
Where t.transaction_id is null
Group By customer_id
14)
https://leetcode.com/problems/product-sales-analysis-i/description/
1068. Product Sales Analysis I
Select p.product_name,
s.year,
s.price
From Product p
Left Join Sales s
On p.product_id = s.product_id
Where s.year is not null and
s.price is not null
15)
https://leetcode.com/problems/replace-employee-id-with-the-unique-identifier/description/
1378. Replace Employee ID With The Unique Identifier
Select e2.unique_id,
e1.name
From Employees e1
Left Join EmployeeUNI e2
On e1.id = e2.id
16)
https://leetcode.com/problems/invalid-tweets/description/
1683. Invalid Tweets
Select tweet_id
From Tweets
Where length(content) > 15
17)
https://leetcode.com/problems/article-views-i/description/
1148. Article Views I
Select distinct author_id as id # the source table has duplicates and we did not remove dups before returning result
From Views
Where author_id = viewer_id
Order By id asc
18)
https://leetcode.com/problems/big-countries/description/
595. Big Countries
Select name, population, area
From World
Where area >= 3000000 Or
population >= 25000000
19)
https://leetcode.com/problems/find-customer-referee/description/
584. Find Customer Referee
Select name
From Customer
where COALESCE(referee_id, 0) <> '2' # as long as you know that 0 has no meaning as a column value
20)
https://leetcode.com/problems/recyclable-and-low-fat-products/description/
1757. Recyclable and Low Fat Products
Select product_id
From Products
Where low_fats = 'Y' and
recyclable = 'Y'
21)
https://leetcode.com/problems/product-sales-analysis-iii/description/
1070. Product Sales Analysis III
Select #s.sale_id,
s.product_id,
x.first_year,
s.quantity,
s.price
From Sales s
Inner Join
(
Select product_id,
min(year) as first_year
From Sales
Group By product_id
) x
On s.product_id = x.product_id and
s.year = x.first_year
22)
https://leetcode.com/problems/tree-node/description/
608. Tree Node
Select
id,
'Root' as type
From Tree
Where p_id is null
Union
#Both a parent and child node
Select distinct t1.id, 'Inner'
From Tree t1
Inner Join Tree t2
On t1.id = t2.p_id
Where t1.p_id is not null
Union
Select id,
'Leaf'
From Tree
Where id not in
(
Select id
From Tree
Where id in (Select p_id From Tree) # nodes that are also parents
)
and p_id is not null
Select id, 'Leaf'
From Tree
Where id not in (Select p_id From Tree)
23)
https://leetcode.com/problems/customers-who-bought-all-products/description/
1045. Customers Who Bought All Products
Select x.customer_id
From
(
Select customer_id,
count(distinct product_key) as num_prod
From Customer
Group By customer_id
) x
Where x.num_prod = (Select count(distinct(product_key)) From Product)
24)
https://leetcode.com/problems/capital-gainloss/description/
1393. Capital Gain/Loss
Select stock_name,
sum(total_gained) as capital_gain_loss
From
(
Select stock_name,
(-1 * sum(price)) as total_gained
From Stocks
Where operation = 'Buy'
Group By stock_name
Union
Select stock_name,
sum(price) as total_gained
From Stocks
Where operation = 'Sell'
Group By stock_name
) x
Group By stock_name
25)
https://leetcode.com/problems/friend-requests-ii-who-has-the-most-friends/description/
602. Friend Requests II: Who Has the Most Friends
Select id,
sum(num_friends) as num
From
(
Select requester_id as id,
count(requester_id) as num_friends
From RequestAccepted
Group By requester_id
Union All
Select accepter_id as id,
count(accepter_id) as num_friends
From RequestAccepted
Group By accepter_id
) x
Group By id
Order By num desc
Limit 1
26)
https://leetcode.com/problems/movie-rating/description/
1341. Movie Rating
Select name as 'results'
From
(
Select u.name , mr.user_id, count(mr.movie_id) as num_reviews
From MovieRating mr
Inner Join Users u
On mr.user_id = u.user_id
Group By mr.user_id
Order By num_reviews desc, u.name asc
Limit 1
) x
Union All
Select title as 'results'
From
(
Select m.title, avg(mr.rating) as avg_rating #, mr.user_id, count(mr.movie_id) as num_reviews
From MovieRating mr
Inner Join Movies m
On mr.movie_id = m.movie_id
Where Month(mr.created_at) = '2' and
Year(mr.created_at) = '2020'
Group By m.movie_id
Order By avg_rating desc, m.title asc
Limit 1
) y
27)
https://leetcode.com/problems/investments-in-2016/description/
585. Investments in 2016
Query 1:
Select round(sum(tiv_2016),2) as tiv_2016
From Insurance i
Where i.tiv_2015 in
(
Select distinct x.tiv_2015
From Insurance x
Where i.pid <> x.pid
)
and
(i.lat, i.lon) not in
(
Select distinct
x.lat,
x.lon
From Insurance x
Where i.pid <> x.pid
)
Query 2:
With CTE1 as
(
Select i.pid,
i.tiv_2015,
i.tiv_2016,
i.lat,
i.lon
From Insurance i
Inner Join Insurance j
On i.tiv_2015 = j.tiv_2015
Where i.pid <> j.pid
)
Select round(sum(tiv_2016),2) as tiv_2016
From Insurance i
Inner Join CTE1 as c1
On i.tiv_2015 = c1.tiv_2015
Where i.pid <> c1.pid and
(
i.lat <> c1.lat or
i.lon <> c1.lon
)
28)
https://leetcode.com/problems/game-play-analysis-iv/description/
550. Game Play Analysis IV
Select round
(
y.con_days
/
(Select count(distinct player_id) From Activity)
,
2
) as fraction
From
(
Select count(distinct a.player_id) as 'con_days'
From Activity a
Inner Join
(
Select player_id,
min(event_date) as event_date
From Activity
Group By player_id
) b
On a.player_id = b.player_id
Where DATEDIFF(a.event_date, b.event_date) = 1 #dont change order or a and b, unless you use absolute value for 1
) y
29)
https://leetcode.com/problems/managers-with-at-least-5-direct-reports/description/
570. Managers with at Least 5 Direct Reports
Select name
From Employee e
Inner Join
(
Select managerId,
count(id) as num_reports
From Employee
Where managerId in
(
#get just the managerID and their names
Select distinct managerId
From Employee
Where managerId is not null
)
Group By managerId
Having count(id) >= 5
) x
On
e.id = x.managerId
Order By name asc
this query will work but is less efficient and harder to follow
Select e.name
From Employee e
Inner Join
(
Select e.managerId,
count(distinct e.id) as num_reports
From
Employee e
Inner Join
(
Select distinct managerId
From Employee
Where managerId is not null
) x
On e.managerId = x.managerId
Where e.managerId is not null
Group By e.managerId
Having count(distinct e.id) >= 5
) y
On e.managerId = y.managerId
30)
https://leetcode.com/problems/rank-scores/description/
178. Rank Scores
Select #id,
score,
#row_number() over (order by score desc ) row_num,
#RANK() over (order by score desc) rnak,
DENSE_RANK() over (order by score desc) 'dense_rank'
From Scores
Order By score desc
31)
https://leetcode.com/problems/second-highest-salary/description/
176. Second Highest Salary
Select max(salary) as SecondHighestSalary
From Employee
Where salary not in
(
Select max(salary)
From Employee
)
32)
https://leetcode.com/problems/employees-whose-manager-left-the-company/description/
1978. Employees Whose Manager Left the Company
Select employee_id
From Employees
Where manager_id not in # the manager was deleted
(
Select distinct employee_id
From Employees
)
and
salary < 30000
Order By employee_id asc
33)
https://leetcode.com/problems/average-time-of-process-per-machine/description/
1661. Average Time of Process per Machine
With CTE_1 as
(
Select a.machine_id,
a.process_id,
(b.timestamp - a.timestamp) processing_time
From Activity a
Inner Join Activity b
On a.process_id = b.process_id and
a.machine_id = b.machine_id
Where b.activity_type = 'end' and
a.activity_type = 'start'
#b.timestamp > a.timestamp
Group By a.machine_id, a.process_id
)
/*
Select *
From CTE_1
*/
Select a.machine_id,
round(avg(a.processing_time),3) as processing_time
From CTE_1 a
Inner Join CTE_1 b
On a.machine_id = b.machine_id
#Where a.process_id <> b.process_id
Group By a.machine_id
34)
https://leetcode.com/problems/list-the-products-ordered-in-a-period/description/
1327. List the Products Ordered in a Period
Select
p.product_name,
sum(o.unit) as 'unit'
From Orders o
Left Join Products p
On o.product_id = p.product_id
Where Month(o.order_date) = '2' and
Year(o.order_date) = '2020' #and
#p.product_id is not null
Group By p.product_name
Having sum(o.unit) >= 100
Select
p.product_name,
sum(o.unit) as 'unit'
From Orders o
Left Join Products p
On o.product_id = p.product_id
Where Month(o.order_date) = '2' and
Year(o.order_date) = '2020' #and
#p.product_id is not null
Group By p.product_name
Having sum(o.unit) >= 100
36)
https://leetcode.com/problems/leetflex-banned-accounts/description/
1747. Leetflex Banned Accounts
Select distinct L1.account_id /*,
L1.ip_address as 'L1.ip_address',
L2.ip_address as 'L2.ip_address',
L2.logout as L2_logout,