-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetcodeSQL50_AK.sql
More file actions
1703 lines (1496 loc) · 75.6 KB
/
LeetcodeSQL50_AK.sql
File metadata and controls
1703 lines (1496 loc) · 75.6 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
/*************************************************************************************************
* LeetCode SQL 50: MySQL Solutions
*
* Source file: README (1).md
* Problem count: 50
* SQL script count: 97
*
* Organization
* 1. Problems follow the order in the README table.
* 2. Each problem includes metadata and every SQL approach found in the README.
* 3. SQL blocks are preserved as written in the README.
*
* Dialect note: The README title indicates MySQL solutions. Individual scripts are kept
* unchanged.
*************************************************************************************************/
/*********************************************************************************************************************
* Index
* 01. 1757. Recyclable and Low Fat Products (Easy) - 1 script
* 02. 584. Find Customer Referee (Easy) - 1 script
* 03. 595. Big Countries (Easy) - 1 script
* 04. 1148. Article Views I (Easy) - 1 script
* 05. 1683. Invalid Tweets (Easy) - 1 script
* 06. 1378. Replace Employee ID With The Unique Identifier (Easy) - 1 script
* 07. 1068. Product Sales Analysis I (Easy) - 1 script
* 08. 1581. Customer Who Visited but Did Not Make Any Transactions (Easy) - 1 script
* 09. 197. Rising Temperature (Easy) - 5 scripts
* 10. 1661. Average Time of Process per Machine (Easy) - 3 scripts
* 11. 577. Employee Bonus (Easy) - 2 scripts
* 12. 1280. Students and Examinations (Easy) - 2 scripts
* 13. 620. Not Boring Movies (Easy) - 2 scripts
* 14. 1251. Average Selling Price (Easy) - 2 scripts
* 15. 570. Managers with at Least 5 Direct Reports (Medium) - 2 scripts
* 16. 1934. Confirmation Rate (Medium) - 3 scripts
* 17. 1075. Project Employees I (Easy) - 2 scripts
* 18. 1633. Percentage of Users Attended a Contest (Easy) - 2 scripts
* 19. 1211. Queries Quality and Percentage (Easy) - 2 scripts
* 20. 1193. Monthly Transactions I (Medium) - 3 scripts
* 21. 1174. Immediate Food Delivery II (Medium) - 1 script
* 22. 550. Game Play Analysis IV (Medium) - 3 scripts
* 23. 2356. Number of Unique Subjects Taught by Each Teacher (Easy) - 1 script
* 24. 1141. User Activity for the Past 30 Days I (Easy) - 3 scripts
* 25. 1070. Product Sales Analysis III (Medium) - 3 scripts
* 26. 596. Classes With at Least 5 Students (Easy) - 2 scripts
* 27. 1729. Find Followers Count (Easy) - 1 script
* 28. 619. Biggest Single Number (Easy) - 1 script
* 29. 1045. Customers Who Bought All Products (Medium) - 1 script
* 30. 1731. The Number of Employees Which Report to Each Employee (Easy) - 2 scripts
* 31. 1789. Primary Department for Each Employee (Easy) - 3 scripts
* 32. 610. Triangle Judgement (Easy) - 1 script
* 33. 180. Consecutive Numbers (Medium) - 2 scripts
* 34. 1164. Product Price at a Given Date (Medium) - 3 scripts
* 35. 1204. Last Person to Fit in the Bus (Medium) - 4 scripts
* 36. 1907. Count Salary Categories (Medium) - 2 scripts
* 37. 1978. Employees Whose Manager Left the Company (Easy) - 2 scripts
* 38. 626. Exchange Seats (Medium) - 3 scripts
* 39. 1341. Movie Rating (Medium) - 3 scripts
* 40. 1321. Restaurant Growth (Medium) - 2 scripts
* 41. 602. Friend Requests II: Who Has the Most Friends (Medium) - 1 script
* 42. 585. Investments in 2016 (Medium) - 2 scripts
* 43. 185. Department Top Three Salaries (Hard) - 1 script
* 44. 1667. Fix Names in a Table (Easy) - 2 scripts
* 45. 1527. Patients With a Condition (Easy) - 2 scripts
* 46. 196. Delete Duplicate Emails (Easy) - 1 script
* 47. 176. Second Highest Salary (Medium) - 3 scripts
* 48. 1484. Group Sold Products By The Date (Easy) - 1 script
* 49. 1327. List the Products Ordered in a Period (Easy) - 2 scripts
* 50. 1517. Find Users With Valid E-Mails (Easy) - 1 script
*********************************************************************************************************************/
/*********************************************************************************************************************
* Problem 01: 1757. Recyclable and Low Fat Products
* Difficulty: Easy
* Key techniques: WHERE filter
* Best performance: not listed
* URL: https://leetcode.com/problems/recyclable-and-low-fat-products/
* Description: Find all products that are both low fat and recyclable.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 1: Primary Solution
***************************************************************************************************/
SELECT product_id FROM products WHERE low_fats = 'Y' AND recyclable = 'Y';
/*********************************************************************************************************************
* Problem 02: 584. Find Customer Referee
* Difficulty: Easy
* Key techniques: WHERE + IS NULL
* Best performance: not listed
* URL: https://leetcode.com/problems/find-customer-referee/
* Description: Find all customers who were not referred by a specific customer.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 1: Primary Solution
***************************************************************************************************/
SELECT name FROM customer WHERE referee_id != 2 OR referee_id IS NULL;
/*********************************************************************************************************************
* Problem 03: 595. Big Countries
* Difficulty: Easy
* Key techniques: WHERE + OR
* Best performance: not listed
* URL: https://leetcode.com/problems/big-countries/
* Description: Find all countries that are either very large in area or have a very large population.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 1: Primary Solution
***************************************************************************************************/
SELECT name, population, area FROM world WHERE area >= 3000000 OR population >= 25000000;
/*********************************************************************************************************************
* Problem 04: 1148. Article Views I
* Difficulty: Easy
* Key techniques: DISTINCT, self-compare
* Best performance: not listed
* URL: https://leetcode.com/problems/article-views-i/
* Description: Find all authors who have viewed at least one of their own articles.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 1: Primary Solution
***************************************************************************************************/
SELECT DISTINCT author_id AS id FROM views WHERE author_id = viewer_id ORDER BY author_id;
/*********************************************************************************************************************
* Problem 05: 1683. Invalid Tweets
* Difficulty: Easy
* Key techniques: LENGTH()
* Best performance: not listed
* URL: https://leetcode.com/problems/invalid-tweets/
* Description: Find all tweets whose content exceeds the allowed character length.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 1: Primary Solution
***************************************************************************************************/
SELECT tweet_id FROM tweets WHERE LENGTH(content) > 15;
/*********************************************************************************************************************
* Problem 06: 1378. Replace Employee ID With The Unique Identifier
* Difficulty: Easy
* Key techniques: LEFT JOIN
* Best performance: not listed
* URL: https://leetcode.com/problems/replace-employee-id-with-the-unique-identifier/
* Description: Display each employee's unique identifier alongside their name, showing null if no mapping exists.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 1: Primary Solution
***************************************************************************************************/
SELECT U.unique_id, E.name FROM employees E LEFT JOIN employeeuni U ON E.id = U.id;
/*********************************************************************************************************************
* Problem 07: 1068. Product Sales Analysis I
* Difficulty: Easy
* Key techniques: JOIN
* Best performance: not listed
* URL: https://leetcode.com/problems/product-sales-analysis-i/
* Description: Report the product name, year, and price for every entry in the sales table.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 1: Primary Solution
***************************************************************************************************/
SELECT P.product_name, S.year, S.price FROM sales S JOIN product P ON S.product_id = P.product_id;
/*********************************************************************************************************************
* Problem 08: 1581. Customer Who Visited but Did Not Make Any Transactions
* Difficulty: Easy
* Key techniques: LEFT JOIN + IS NULL
* Best performance: not listed
* URL: https://leetcode.com/problems/customer-who-visited-but-did-not-make-any-transactions/
* Description: Find customers who visited but made no transactions, along with how many times that occurred.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 1: Primary Solution
***************************************************************************************************/
SELECT V.customer_id, COUNT(*) AS count_no_trans
FROM Visits V
LEFT JOIN Transactions T
ON V.visit_id = T.visit_id
WHERE T.visit_id IS NULL
GROUP BY V.customer_id;
/*********************************************************************************************************************
* Problem 09: 197. Rising Temperature
* Difficulty: Easy
* Key techniques: LAG, Self Join, EXISTS
* Best performance: 98.38%
* URL: https://leetcode.com/problems/rising-temperature/
* Description: Find all dates where the temperature was higher than the previous day's temperature.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 5: Using LAG
* Performance: Beats 39.26%
***************************************************************************************************/
SELECT id
FROM (
SELECT id, recordDate, temperature,
LAG(temperature) OVER (ORDER BY recordDate) AS prev_temp,
LAG(recordDate) OVER (ORDER BY recordDate) AS prev_date
FROM weather
) w
WHERE prev_date = recordDate - INTERVAL '1' DAY
AND temperature > prev_temp;
/***************************************************************************************************
* Approach 2 of 5: Using Self Join
* Performance: Beats 79.80%
***************************************************************************************************/
SELECT w1.id
FROM weather w1
JOIN weather w2
ON w2.recordDate = w1.recordDate - INTERVAL '1' DAY
WHERE w1.temperature > w2.temperature;
/***************************************************************************************************
* Approach 3 of 5: Using Correlated Subquery
* Performance: Beats 86.73%
***************************************************************************************************/
SELECT id FROM weather w1
WHERE w1.temperature > (
SELECT w2.temperature FROM weather w2
WHERE w2.recordDate = w1.recordDate - INTERVAL '1' DAY
);
/***************************************************************************************************
* Approach 4 of 5: Using EXISTS
* Performance: Beats 93.08%
***************************************************************************************************/
SELECT w1.id
FROM Weather w1
WHERE EXISTS (
SELECT 1
FROM Weather w2
WHERE w2.recordDate = w1.recordDate - INTERVAL '1' DAY
AND w1.temperature > w2.temperature
);
/***************************************************************************************************
* Approach 5 of 5: Using Window Function with DATE_DIFF
* Performance: Beats 98.38%
***************************************************************************************************/
SELECT id
FROM (
SELECT
id,
recordDate,
temperature,
LAG(recordDate) OVER (ORDER BY recordDate) AS prev_date,
LAG(temperature) OVER (ORDER BY recordDate) AS prev_temp
FROM Weather
)
WHERE DATE_DIFF(recordDate, prev_date, DAY) = 1
AND temperature > prev_temp;
/*********************************************************************************************************************
* Problem 10: 1661. Average Time of Process per Machine
* Difficulty: Easy
* Key techniques: Conditional Agg, Self Join
* Best performance: 77.22%
* URL: https://leetcode.com/problems/average-time-of-process-per-machine/
* Description: Calculate the average time each machine takes to complete a process across all its process runs.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 3: Using Conditional Aggregation in Subquery
* Performance: Beats 63.83%
***************************************************************************************************/
SELECT machine_id, ROUND(AVG(process_time), 3) AS processing_time
FROM (
SELECT machine_id, process_id,
MAX(CASE WHEN activity_type = 'end' THEN timestamp END)
-
MAX(CASE WHEN activity_type = 'start' THEN timestamp END)
AS process_time
FROM activity
GROUP BY machine_id, process_id
) t
GROUP BY machine_id;
/***************************************************************************************************
* Approach 2 of 3: Using Correlated Subquery
* Performance: Beats 68.33%
***************************************************************************************************/
SELECT machine_id, ROUND(AVG((SELECT a2.timestamp FROM activity a2
WHERE a2.machine_id = a1.machine_id
AND a2.process_id = a1.process_id
AND a2.activity_type = 'end') - a1.timestamp), 3) AS processing_time
FROM activity a1
WHERE a1.activity_type = 'start'
GROUP BY machine_id;
/***************************************************************************************************
* Approach 3 of 3: Using Self Join
* Performance: Beats 77.22%
***************************************************************************************************/
SELECT s.machine_id, ROUND(AVG(e.timestamp - s.timestamp), 3) AS processing_time
FROM activity s
JOIN activity e
ON s.machine_id = e.machine_id
AND s.process_id = e.process_id
AND e.activity_type = 'end'
WHERE s.activity_type = 'start'
GROUP BY s.machine_id;
/*********************************************************************************************************************
* Problem 11: 577. Employee Bonus
* Difficulty: Easy
* Key techniques: LEFT JOIN, COALESCE
* Best performance: not listed
* URL: https://leetcode.com/problems/employee-bonus/
* Description: Report the name and bonus of each employee whose bonus is less than 1000 or who has no bonus at
* all.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 2: Simple
***************************************************************************************************/
SELECT e.name, b.bonus FROM employee e LEFT JOIN bonus b ON e.empId = b.empId
WHERE bonus < 1000 OR bonus IS NULL;
/***************************************************************************************************
* Approach 2 of 2: Using COALESCE
***************************************************************************************************/
SELECT e.name, b.bonus FROM employee e LEFT JOIN bonus b ON e.empId = b.empId
WHERE COALESCE(b.bonus, 0) < 1000;
/*********************************************************************************************************************
* Problem 12: 1280. Students and Examinations
* Difficulty: Easy
* Key techniques: CROSS JOIN, LEFT JOIN
* Best performance: 85.65%
* URL: https://leetcode.com/problems/students-and-examinations/
* Description: For every student and every subject, report how many times that student attended an exam for that
* subject.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 2: Using CROSS JOIN
* Performance: Beats 52.62%
***************************************************************************************************/
SELECT st.student_id, st.student_name, su.subject_name, COUNT(e.subject_name) AS attended_exams
FROM students st CROSS JOIN subjects su LEFT JOIN examinations e
ON st.student_id = e.student_id AND e.subject_name = su.subject_name
GROUP BY st.student_id, st.student_name, su.subject_name
ORDER BY st.student_id, st.student_name;
/***************************************************************************************************
* Approach 2 of 2: Using LEFT JOIN
* Performance: Beats 85.65%
***************************************************************************************************/
SELECT S.student_id, S.student_name, Su.subject_name, COUNT(E.student_id) AS attended_exams
FROM students S
JOIN subjects Su
LEFT JOIN examinations E
ON S.student_id = E.student_id
AND Su.subject_name = E.subject_name
GROUP BY S.student_id, Su.subject_name
ORDER BY student_id, subject_name;
/*********************************************************************************************************************
* Problem 13: 620. Not Boring Movies
* Difficulty: Easy
* Key techniques: MOD, Bitwise &
* Best performance: 81.48%
* URL: https://leetcode.com/problems/not-boring-movies/
* Description: Find movies with an odd-numbered ID and a description that is not "boring", sorted by rating
* descending.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 2: Using MOD (%)
* Performance: Beats 79.67%
***************************************************************************************************/
SELECT id, movie, description, rating FROM cinema
WHERE id % 2 = 1 AND description != 'boring'
ORDER BY rating DESC;
/***************************************************************************************************
* Approach 2 of 2: Using Bitwise AND (&)
* Performance: Beats 81.48%
***************************************************************************************************/
SELECT id, movie, description, rating FROM cinema
WHERE id & 1 = 1 AND description <> 'boring'
ORDER BY rating DESC;
/*********************************************************************************************************************
* Problem 14: 1251. Average Selling Price
* Difficulty: Easy
* Key techniques: LEFT JOIN, NULLIF, pre-agg
* Best performance: 81.32%
* URL: https://leetcode.com/problems/average-selling-price/
* Description: Calculate the average selling price for each product weighted by the number of units sold.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 2: JOIN first, AGG later
* Performance: Beats 35.36%
***************************************************************************************************/
SELECT P.product_id,
ROUND(COALESCE(SUM(P.price * U.units) / NULLIF(SUM(U.units), 0), 0), 2) AS average_price
FROM prices P
LEFT JOIN unitssold U
ON P.product_id = U.product_id
AND U.purchase_date BETWEEN P.start_date AND P.end_date
GROUP BY P.product_id;
/***************************************************************************************************
* Approach 2 of 2: AGG first, JOIN later
* Performance: Beats 81.32%
***************************************************************************************************/
SELECT P.product_id,
ROUND(IFNULL(SUM(P.price * units_sum) / SUM(units_sum), 0), 2) AS average_price
FROM prices P
LEFT JOIN (
SELECT product_id, purchase_date, SUM(units) AS units_sum
FROM unitssold
GROUP BY product_id, purchase_date
) U
ON P.product_id = U.product_id
AND U.purchase_date BETWEEN P.start_date AND P.end_date
GROUP BY P.product_id;
/*********************************************************************************************************************
* Problem 15: 570. Managers with at Least 5 Direct Reports
* Difficulty: Medium
* Key techniques: IN, JOIN + HAVING
* Best performance: 93.51%
* URL: https://leetcode.com/problems/managers-with-at-least-5-direct-reports/
* Description: Find managers who have at least five employees reporting directly to them.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 2: Using IN
* Performance: Beats 91.05%
***************************************************************************************************/
SELECT e.name FROM employee e
WHERE e.id IN (SELECT managerId FROM employee
WHERE managerId IS NOT NULL
GROUP BY managerId
HAVING COUNT(*) > 4);
/***************************************************************************************************
* Approach 2 of 2: Using JOIN
* Performance: Beats 93.51%
***************************************************************************************************/
SELECT e.name FROM employee e
JOIN (
SELECT managerId FROM employee
WHERE managerId IS NOT NULL
GROUP BY managerId
HAVING COUNT(*) > 4
) m ON e.id = m.managerId;
/*********************************************************************************************************************
* Problem 16: 1934. Confirmation Rate
* Difficulty: Medium
* Key techniques: AVG, IF, pre-agg subquery
* Best performance: 82.92%
* URL: https://leetcode.com/problems/confirmation-rate/
* Description: Calculate the rate at which each user confirmed their messages out of all messages sent to them.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 3: Using COALESCE
* Performance: Beats 39.9%
***************************************************************************************************/
SELECT S.user_id,
ROUND(COALESCE(AVG(C.action = 'confirmed'), 0), 2) AS confirmation_rate
FROM signups S
LEFT JOIN confirmations C ON S.user_id = C.user_id
GROUP BY user_id;
/***************************************************************************************************
* Approach 2 of 3: Using IF
* Performance: Beats 64.95%
***************************************************************************************************/
SELECT S.user_id,
ROUND(AVG(IF(c.action = 'confirmed', 1, 0)), 2) AS confirmation_rate
FROM signups S
LEFT JOIN confirmations C ON S.user_id = C.user_id
GROUP BY user_id;
/***************************************************************************************************
* Approach 3 of 3: AGG first, JOIN later
* Performance: Beats 82.92%
***************************************************************************************************/
SELECT s.user_id,
ROUND(COALESCE(c.confirmed / c.total, 0), 2) AS confirmation_rate
FROM Signups s
LEFT JOIN (
SELECT user_id,
SUM(action = 'confirmed') AS confirmed,
COUNT(*) AS total
FROM Confirmations
GROUP BY user_id
) c ON s.user_id = c.user_id;
/*********************************************************************************************************************
* Problem 17: 1075. Project Employees I
* Difficulty: Easy
* Key techniques: AVG, SUM/COUNT
* Best performance: 85.58%
* URL: https://leetcode.com/problems/project-employees-i/
* Description: Find the average years of experience of employees assigned to each project.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 2: Using AVG
* Performance: Beats 70.76%
***************************************************************************************************/
SELECT project_id, ROUND(AVG(E.experience_years), 2) AS average_years
FROM project P JOIN employee E ON P.employee_id = E.employee_id
GROUP BY project_id;
/***************************************************************************************************
* Approach 2 of 2: Using SUM / COUNT
* Performance: Beats 85.58%
***************************************************************************************************/
SELECT project_id, ROUND(SUM(E.experience_years)/COUNT(*), 2) AS average_years
FROM project P JOIN employee E ON P.employee_id = E.employee_id
GROUP BY project_id;
/*********************************************************************************************************************
* Problem 18: 1633. Percentage of Users Attended a Contest
* Difficulty: Easy
* Key techniques: Scalar subquery, CROSS JOIN
* Best performance: 73.76%
* URL: https://leetcode.com/problems/percentage-of-users-attended-a-contest/
* Description: Calculate the percentage of all users who registered for each contest, sorted by percentage then
* contest ID.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 2: Using Scalar Subquery
* Performance: Beats 73.76%
***************************************************************************************************/
SELECT contest_id,
ROUND((COUNT(user_id)/(SELECT COUNT(*) FROM users)) * 100, 2) AS percentage
FROM register
GROUP BY contest_id
ORDER BY percentage DESC, contest_id;
/***************************************************************************************************
* Approach 2 of 2: Using CROSS JOIN
* Performance: Beats 73.23%
***************************************************************************************************/
SELECT contest_id,
ROUND((COUNT(R.user_id)/ U.total) * 100, 2) AS percentage
FROM register R
CROSS JOIN (SELECT COUNT(*) AS total FROM users) U
GROUP BY contest_id
ORDER BY percentage DESC, contest_id;
/*********************************************************************************************************************
* Problem 19: 1211. Queries Quality and Percentage
* Difficulty: Easy
* Key techniques: AVG, SUM, CASE WHEN
* Best performance: 96.29%
* URL: https://leetcode.com/problems/queries-quality-and-percentage/
* Description: For each query, calculate its average quality rating and the percentage of its results rated as
* poor.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 2: Using SUM
* Performance: Beats 42.94%
***************************************************************************************************/
SELECT query_name,
ROUND(AVG(rating/position), 2) AS quality,
ROUND(SUM(rating < 3)*100/COUNT(rating), 2) AS poor_query_percentage
FROM queries
GROUP BY query_name;
/***************************************************************************************************
* Approach 2 of 2: Using CASE WHEN
* Performance: Beats 96.29%
***************************************************************************************************/
SELECT query_name,
ROUND(AVG(rating / position), 2) AS quality,
ROUND(AVG(CASE WHEN rating < 3 THEN 1 ELSE 0 END) * 100, 2) AS poor_query_percentage
FROM queries
WHERE query_name IS NOT NULL
GROUP BY query_name;
/*********************************************************************************************************************
* Problem 20: 1193. Monthly Transactions I
* Difficulty: Medium
* Key techniques: DATE_FORMAT, LEFT, CASE WHEN
* Best performance: 87.21%
* URL: https://leetcode.com/problems/monthly-transactions-i/
* Description: For each month and country, summarize the total number of transactions and the count and amount of
* approved ones.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 3: Using DATE_FORMAT
* Performance: Beats 39.53%
***************************************************************************************************/
SELECT DATE_FORMAT(trans_date, '%Y-%m') AS month, country,
COUNT(trans_date) AS trans_count,
SUM(state='approved') AS approved_count,
SUM(amount) AS trans_total_amount,
SUM(CASE WHEN state='approved' THEN amount ELSE 0 END) AS approved_total_amount
FROM transactions
GROUP BY month, country;
/***************************************************************************************************
* Approach 2 of 3: Using LEFT
* Performance: Beats 78.97%
***************************************************************************************************/
SELECT LEFT(trans_date, 7) AS month, country,
COUNT(trans_date) AS trans_count,
SUM(state='approved') AS approved_count,
SUM(amount) AS trans_total_amount,
SUM(CASE WHEN state='approved' THEN amount ELSE 0 END) AS approved_total_amount
FROM transactions
GROUP BY month, country;
/***************************************************************************************************
* Approach 3 of 3: Using CASE WHEN x2
* Performance: Beats 87.21%
***************************************************************************************************/
SELECT LEFT(trans_date, 7) AS month, country,
COUNT(trans_date) AS trans_count,
SUM(CASE WHEN state = 'approved' THEN 1 ELSE 0 END) AS approved_count,
SUM(amount) AS trans_total_amount,
SUM(CASE WHEN state='approved' THEN amount ELSE 0 END) AS approved_total_amount
FROM transactions
GROUP BY month, country;
/*********************************************************************************************************************
* Problem 21: 1174. Immediate Food Delivery II
* Difficulty: Medium
* Key techniques: Subquery, MIN
* Best performance: 90.40%
* URL: https://leetcode.com/problems/immediate-food-delivery-ii/
* Description: Find the percentage of customers whose first-ever order was an immediate delivery.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 1: Primary Solution
* Performance: Beats 90.67%
***************************************************************************************************/
SELECT ROUND(SUM(first_order = first_del) * 100 / COUNT(*), 2) AS immediate_percentage
FROM (
SELECT customer_id, MIN(order_date) AS first_order,
MIN(customer_pref_delivery_date) AS first_del
FROM delivery
GROUP BY customer_id
) f;
/*********************************************************************************************************************
* Problem 22: 550. Game Play Analysis IV
* Difficulty: Medium
* Key techniques: CTE, Subquery, Window Function
* Best performance: 96.18%
* URL: https://leetcode.com/problems/game-play-analysis-iv/
* Description: Find the fraction of players who logged in again the day immediately after their first login.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 3: Using CTE
* Performance: Beats 18.92%
***************************************************************************************************/
WITH first_login AS (
SELECT player_id, MIN(event_date) AS first_date
FROM activity
GROUP BY player_id
)
SELECT ROUND(COUNT(A.player_id) / COUNT(F.player_id), 2) AS fraction
FROM first_login F
LEFT JOIN activity A
ON F.player_id = A.player_id
AND A.event_date = DATE_ADD(F.first_date, INTERVAL 1 DAY);
/***************************************************************************************************
* Approach 2 of 3: Using Subquery
* Performance: Beats 82.32%
***************************************************************************************************/
SELECT ROUND(COUNT(A.player_id) / COUNT(F.player_id), 2) AS fraction
FROM (
SELECT player_id, MIN(event_date) AS first_date
FROM activity
GROUP BY player_id
) F
LEFT JOIN activity A
ON F.player_id = A.player_id
AND A.event_date = DATE_ADD(F.first_date, INTERVAL 1 DAY);
/***************************************************************************************************
* Approach 3 of 3: Using Window Function
* Performance: Beats 96.18%
***************************************************************************************************/
SELECT ROUND(
SUM(CASE WHEN DATEDIFF(event_date, first_date) = 1 THEN 1 ELSE 0 END) /
COUNT(DISTINCT player_id), 2
) AS fraction
FROM (
SELECT player_id, event_date,
MIN(event_date) OVER (PARTITION BY player_id) AS first_date
FROM Activity
) T;
/*********************************************************************************************************************
* Problem 23: 2356. Number of Unique Subjects Taught by Each Teacher
* Difficulty: Easy
* Key techniques: COUNT DISTINCT
* Best performance: 90.92%
* URL: https://leetcode.com/problems/number-of-unique-subjects-taught-by-each-teacher/
* Description: Count how many distinct subjects each teacher teaches across all departments.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 1: Primary Solution
* Performance: Beats 91.25%
***************************************************************************************************/
SELECT teacher_id, COUNT(DISTINCT subject_id) AS cnt
FROM teacher
GROUP BY teacher_id;
/*********************************************************************************************************************
* Problem 24: 1141. User Activity for the Past 30 Days I
* Difficulty: Easy
* Key techniques: BETWEEN, COUNT DISTINCT
* Best performance: 81.29%
* URL: https://leetcode.com/problems/user-activity-for-the-past-30-days-i/
* Description: Count the number of active users per day within a specific 30-day window.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 3: Using BETWEEN
* Performance: Beats 60.32%
***************************************************************************************************/
SELECT activity_date AS day, COUNT(DISTINCT user_id) AS active_users
FROM activity
WHERE activity_date BETWEEN '2019-06-28' AND '2019-07-27'
GROUP BY activity_date;
/***************************************************************************************************
* Approach 2 of 3: Using Subquery
* Performance: Beats 57.18%
***************************************************************************************************/
SELECT activity_date AS day, COUNT(user_id) AS active_users
FROM (
SELECT DISTINCT activity_date, user_id
FROM activity
WHERE activity_date BETWEEN '2019-06-28' AND '2019-07-27'
) A
GROUP BY activity_date;
/***************************************************************************************************
* Approach 3 of 3: Using Direct Range Operators
* Performance: Beats 81.29%
***************************************************************************************************/
SELECT activity_date AS day, COUNT(DISTINCT user_id) AS active_users
FROM activity
WHERE activity_date > '2019-06-27' AND activity_date <= '2019-07-27'
GROUP BY activity_date;
/*********************************************************************************************************************
* Problem 25: 1070. Product Sales Analysis III
* Difficulty: Medium
* Key techniques: JOIN, RANK(), Tuple IN
* Best performance: 84.71%
* URL: https://leetcode.com/problems/product-sales-analysis-iii/
* Description: For each product, report the first year it was ever sold along with the quantity and price that
* year.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 3: Using JOIN
* Performance: Beats 18.85%
***************************************************************************************************/
SELECT S.product_id, S.year AS first_year, S.quantity, S.price
FROM sales S
JOIN (
SELECT product_id, MIN(year) AS first_year FROM sales
GROUP BY product_id
) F ON S.product_id = F.product_id AND S.year = F.first_year;
/***************************************************************************************************
* Approach 2 of 3: Using RANK()
* Performance: Beats 44.65%
***************************************************************************************************/
SELECT product_id, year AS first_year, quantity, price
FROM (
SELECT product_id, year, quantity, price,
RANK() OVER (PARTITION BY product_id ORDER BY year) AS rnk
FROM sales
) R
WHERE rnk = 1;
/***************************************************************************************************
* Approach 3 of 3: Using Tuple IN
* Performance: Beats 84.71%
***************************************************************************************************/
SELECT product_id, year AS first_year, quantity, price
FROM sales
WHERE (product_id, year) IN (
SELECT product_id, MIN(year) FROM sales
GROUP BY product_id
);
/*********************************************************************************************************************
* Problem 26: 596. Classes With at Least 5 Students
* Difficulty: Easy
* Key techniques: HAVING, COUNT DISTINCT
* Best performance: not listed
* URL: https://leetcode.com/problems/classes-more-than-5-students/
* Description: Find all classes that have at least five students enrolled.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 2: Using DISTINCT
***************************************************************************************************/
SELECT class
FROM courses
GROUP BY class
HAVING COUNT(DISTINCT student) >= 5;
/***************************************************************************************************
* Approach 2 of 2: Simple
***************************************************************************************************/
SELECT class
FROM courses
GROUP BY 1
HAVING COUNT(DISTINCT student) > 4;
/*********************************************************************************************************************
* Problem 27: 1729. Find Followers Count
* Difficulty: Easy
* Key techniques: COUNT, GROUP BY
* Best performance: 86.10%
* URL: https://leetcode.com/problems/find-followers-count/
* Description: Report the number of followers each user has, sorted by user ID.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 1: Primary Solution
* Performance: Beats 86.10%
***************************************************************************************************/
SELECT user_id, COUNT(follower_id) AS followers_count
FROM followers
GROUP BY user_id
ORDER BY user_id;
/*********************************************************************************************************************
* Problem 28: 619. Biggest Single Number
* Difficulty: Easy
* Key techniques: Subquery, MAX, HAVING
* Best performance: 81.94%
* URL: https://leetcode.com/problems/biggest-single-number/
* Description: Find the largest number that appears exactly once in the table, or null if no such number exists.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 1: Primary Solution
* Performance: Beats 81.94%
***************************************************************************************************/
SELECT MAX(num) AS num
FROM (
SELECT num FROM mynumbers
GROUP BY num
HAVING COUNT(*) = 1
) N;
/*********************************************************************************************************************
* Problem 29: 1045. Customers Who Bought All Products
* Difficulty: Medium
* Key techniques: HAVING, COUNT DISTINCT
* Best performance: 75.88%
* URL: https://leetcode.com/problems/customers-who-bought-all-products/
* Description: Find all customers who have purchased every single product in the product table.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 1: Primary Solution
* Performance: Beats 75.88%
***************************************************************************************************/
SELECT customer_id FROM customer
GROUP BY customer_id
HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM product);
/*********************************************************************************************************************
* Problem 30: 1731. The Number of Employees Which Report to Each Employee
* Difficulty: Easy
* Key techniques: Self Join, Subquery
* Best performance: 62.73%
* URL: https://leetcode.com/problems/the-number-of-employees-which-report-to-each-employee/
* Description: For each manager, report the number of direct reports and the average age of those reports rounded
* to the nearest integer.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 2: Subquery Aggregates First, Then Join
* Performance: Beats 44.82%
***************************************************************************************************/
SELECT E.employee_id, E.name, M.reports_count, M.average_age
FROM employees E
JOIN (
SELECT reports_to, COUNT(*) AS reports_count, ROUND(AVG(age)) AS average_age
FROM employees
WHERE reports_to IS NOT NULL
GROUP BY reports_to
) M ON E.employee_id = M.reports_to
ORDER BY E.employee_id;
/***************************************************************************************************
* Approach 2 of 2: Direct Join, Aggregates After
* Performance: Beats 62.73%
***************************************************************************************************/
SELECT M.employee_id, M.name, COUNT(*) AS reports_count, ROUND(AVG(E.age)) AS average_age
FROM Employees M
JOIN Employees E ON E.reports_to = M.employee_id
GROUP BY M.employee_id
ORDER BY M.employee_id;
/*********************************************************************************************************************
* Problem 31: 1789. Primary Department for Each Employee
* Difficulty: Easy
* Key techniques: UNION ALL, PARTITION BY
* Best performance: 70.77%
* URL: https://leetcode.com/problems/primary-department-for-each-employee/
* Description: Find the primary department for each employee — the single department if they only belong to one,
* or the one flagged as primary.
*********************************************************************************************************************/
/***************************************************************************************************
* Approach 1 of 3: Using UNION ALL
* Performance: Beats 46.54%
***************************************************************************************************/
SELECT employee_id, department_id FROM employee
GROUP BY employee_id
HAVING COUNT(*) = 1
UNION ALL
SELECT employee_id, department_id FROM employee
WHERE primary_flag = 'Y';
/***************************************************************************************************
* Approach 2 of 3: Using PARTITION BY
* Performance: Beats 63.04%
***************************************************************************************************/
SELECT employee_id, department_id
FROM (
SELECT employee_id, department_id, primary_flag,
COUNT(*) OVER (PARTITION BY employee_id) AS dept_count
FROM employee
) E
WHERE primary_flag = 'Y' OR dept_count = 1;
/***************************************************************************************************
* Approach 3 of 3: Simple
* Performance: Beats 70.77%
***************************************************************************************************/
SELECT employee_id, department_id FROM employee
WHERE primary_flag = 'Y'
OR employee_id IN (
SELECT employee_id FROM employee
GROUP BY employee_id
HAVING COUNT(*) = 1
);