-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathleetcode.sql
More file actions
11522 lines (10482 loc) · 419 KB
/
Copy pathleetcode.sql
File metadata and controls
11522 lines (10482 loc) · 419 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
/*176. Second Highest Salary (Medium)
SQL Schema
Table: Employee
+-------------+------+
| Column Name | Type |
+-------------+------+
| id | int |
| salary | int |
+-------------+------+
id is the primary key column for this table. Each row of this table contains
information about the salary of an employee.
Write an SQL query to report the second highest salary from the Employee table.
If there is no second highest salary, the query should report null. The query
result format is in the following example.
Example 1:
Input:
Employee table: +----+--------+
| id | salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
Output: +---------------------+
| SecondHighestSalary |
+---------------------+
| 200 |
+---------------------+
Example 2:
Input:
Employee table: +----+--------+
| id | salary |
+----+--------+
| 1 | 100 |
+----+--------+
Output: +---------------------+
| SecondHighestSalary |
+---------------------+
| null |
+---------------------+*/
SELECT
IFNULL(
(SELECT DISTINCT Salary #parenthesis is necessary!
FROM Employee
ORDER BY Salary DESC LIMIT 1 OFFSET 1),
NULL) AS SecondHighestSalary
/*177. Nth Highest Salary (Medium)
SQL Schema
Table: Employee
+-------------+------+
| Column Name | Type |
+-------------+------+
| id | int |
| salary | int |
+-------------+------+
id is the primary key column for this table. Each row of this table contains
information about the salary of an employee.
Write an SQL query to report the nth highest salary from the Employee table. If
there is no nth highest salary, the query should report null. The query result
format is in the following example.
Example 1:
Input:
Employee table: +----+--------+
| id | salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
n = 2
Output: +------------------------+
| getNthHighestSalary(2) |
+------------------------+
| 200 |
+------------------------+
Example 2:
Input:
Employee table: +----+--------+
| id | salary |
+----+--------+
| 1 | 100 |
+----+--------+
n = 2
Output: +------------------------+
| getNthHighestSalary(2) |
+------------------------+
| null |
+------------------------+*/
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
RETURN (
SELECT DISTINCT Salary
FROM Employee e1
WHERE N-1 = (SELECT COUNT(DISTINCT Salary) FROM Employee e2 WHERE e1.Salary < e2.Salary)
);
END
/*178. Rank Scores (Medium)
SQL Schema
Table: Scores
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| score | decimal |
+-------------+---------+
id is the primary key for this table. Each row of this table contains the score
of a game. Score is a floating point value with two decimal places.
Write an SQL query to rank the scores. The ranking should be calculated
according to the following rules:
* The scores should be ranked from the highest to the lowest.
* If there is a tie between two scores, both should have the same ranking.
* After a tie, the next ranking number should be the next consecutive integer
value. In other words, there should be no holes between ranks.
Return the result table ordered by score in descending order. The query result
format is in the following example.
Example 1:
Input:
Scores table: +----+-------+
| id | score |
+----+-------+
| 1 | 3.50 |
| 2 | 3.65 |
| 3 | 4.00 |
| 4 | 3.85 |
| 5 | 4.00 |
| 6 | 3.65 |
+----+-------+
Output: +-------+------+
| score | rank |
+-------+------+
| 4.00 | 1 |
| 4.00 | 1 |
| 3.85 | 2 |
| 3.65 | 3 |
| 3.65 | 3 |
| 3.50 | 4 |
+-------+------+*/
SELECT Score, @i:=@i+(@prev <> (@prev:=Score)) AS Rank
FROM Scores, (SELECT @i:=0, @prev:=-1) init
ORDER BY Score DESC;
/*180. Consecutive Numbers (Medium)
SQL Schema
Table: Logs
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| num | varchar |
+-------------+---------+
id is the primary key for this table. id is an autoincrement column.
Write an SQL query to find all numbers that appear at least three times
consecutively. Return the result table in any order. The query result format is
in the following example.
Example 1:
Input:
Logs table: +----+-----+
| id | num |
+----+-----+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 1 |
| 6 | 2 |
| 7 | 2 |
+----+-----+
Output: +-----------------+
| ConsecutiveNums |
+-----------------+
| 1 |
+-----------------+
Explanation: 1 is the only number that appears consecutively for at least three
times.*/
SELECT DISTINCT Num AS ConsecutiveNums
FROM
(SELECT Num, @i:=@j AS i, @j:=@k AS j, @k:=CAST(Num AS CHAR) AS k
FROM Logs, (SELECT @i:=NULL, @j:=NULL, @k:=NULL) a) b
WHERE i = j AND j = k;
/*184. Department Highest Salary (Medium)
SQL Schema
Table: Employee
+--------------+---------+
| Column Name | Type |
+--------------+---------+
| id | int |
| name | varchar |
| salary | int |
| departmentId | int |
+--------------+---------+
id is the primary key column for this table. departmentId is a foreign key of
the ID from the Department table. Each row of this table indicates the ID, name,
and salary of an employee. It also contains the ID of their department.
Table: Department
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| name | varchar |
+-------------+---------+
id is the primary key column for this table. Each row of this table indicates
the ID of a department and its name.
Write an SQL query to find employees who have the highest salary in each of the
departments. Return the result table in any order. The query result format is
in the following example.
Example 1:
Input:
Employee table: +----+-------+--------+--------------+
| id | name | salary | departmentId |
+----+-------+--------+--------------+
| 1 | Joe | 70000 | 1 |
| 2 | Jim | 90000 | 1 |
| 3 | Henry | 80000 | 2 |
| 4 | Sam | 60000 | 2 |
| 5 | Max | 90000 | 1 |
+----+-------+--------+--------------+
Department table: +----+-------+
| id | name |
+----+-------+
| 1 | IT |
| 2 | Sales |
+----+-------+
Output: +------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT | Jim | 90000 |
| Sales | Henry | 80000 |
| IT | Max | 90000 |
+------------+----------+--------+
Explanation: Max and Jim both have the highest salary in the IT department and
Henry has the highest salary in the Sales department.*/
SELECT a.Name AS Department, b.Name AS Employee, Salary
FROM
Department a,
Employee b
WHERE a.Id = b.DepartmentId AND Salary = (SELECT MAX(Salary) FROM Employee c WHERE b.DepartmentId = c.DepartmentId);
/*534. Game Play Analysis III (Medium)
SQL Schema
Table: Activity
+--------------+---------+
| Column Name | Type |
+--------------+---------+
| player_id | int |
| device_id | int |
| event_date | date |
| games_played | int |
+--------------+---------+
(player_id, event_date) is the primary key of this table. This table shows the
activity of players of some games. Each row is a record of a player who logged
in and played a number of games (possibly 0) before logging out on someday
using some device.
Write an SQL query to report for each player and date, how many games played so
far by the player. That is, the total number of games played by the player
until that date. Check the example for clarity. Return the result table in any
order. The query result format is in the following example.
Example 1:
Input:
Activity table: +-----------+-----------+------------+--------------+
| player_id | device_id | event_date | games_played |
+-----------+-----------+------------+--------------+
| 1 | 2 | 2016-03-01 | 5 |
| 1 | 2 | 2016-05-02 | 6 |
| 1 | 3 | 2017-06-25 | 1 |
| 3 | 1 | 2016-03-02 | 0 |
| 3 | 4 | 2018-07-03 | 5 |
+-----------+-----------+------------+--------------+
Output: +-----------+------------+---------------------+
| player_id | event_date | games_played_so_far |
+-----------+------------+---------------------+
| 1 | 2016-03-01 | 5 |
| 1 | 2016-05-02 | 11 |
| 1 | 2017-06-25 | 12 |
| 3 | 2016-03-02 | 0 |
| 3 | 2018-07-03 | 5 |
+-----------+------------+---------------------+
Explanation: For the player with id 1, 5 + 6 = 11 games played by 2016-05-02,
and 5 + 6 + 1 = 12 games played by 2017-06-25. For the player with
id 3, 0 + 5 = 5 games played by 2018-07-03. Note that for each
player we only care about the days when the player logged in.*/
SELECT
a.player_id,
a.event_date,
SUM(b.games_played) AS games_played_so_far
FROM
Activity a, Activity b
WHERE a.event_date >= b.event_date AND a.player_id = b.player_id
GROUP BY a.player_id, a.event_date;
/*550. Game Play Analysis IV (Medium)
SQL Schema
Table: Activity
+--------------+---------+
| Column Name | Type |
+--------------+---------+
| player_id | int |
| device_id | int |
| event_date | date |
| games_played | int |
+--------------+---------+
(player_id, event_date) is the primary key of this table. This table shows the
activity of players of some games. Each row is a record of a player who logged
in and played a number of games (possibly 0) before logging out on someday
using some device.
Write an SQL query to report the fraction of players that logged in again on
the day after the day they first logged in, rounded to 2 decimal places. In
other words, you need to count the number of players that logged in for at
least two consecutive days starting from their first login date, then divide
that number by the total number of players. The query result format is in the
following example.
Example 1:
Input:
Activity table: +-----------+-----------+------------+--------------+
| player_id | device_id | event_date | games_played |
+-----------+-----------+------------+--------------+
| 1 | 2 | 2016-03-01 | 5 |
| 1 | 2 | 2016-03-02 | 6 |
| 2 | 3 | 2017-06-25 | 1 |
| 3 | 1 | 2016-03-02 | 0 |
| 3 | 4 | 2018-07-03 | 5 |
+-----------+-----------+------------+--------------+
Output: +-----------+
| fraction |
+-----------+
| 0.33 |
+-----------+
Explanation: Only the player with id 1 logged back in after the first day he
had logged in so the answer is 1/3 = 0.33*/
SELECT
ROUND(COUNT(*)/(SELECT COUNT(DISTINCT player_id) FROM Activity), 2) AS fraction
FROM
Activity
WHERE
CONCAT(player_id, event_date) IN (SELECT CONCAT(player_id, ADDDATE(MIN(event_date), 1)) FROM Activity GROUP BY player_id);
/*570. Managers with at Least 5 Direct Reports (Medium)
SQL Schema
Table: Employee
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| name | varchar |
| department | varchar |
| managerId | int |
+-------------+---------+
id is the primary key column for this table. Each row of this table indicates
the name of an employee, their department, and the id of their manager. If
managerId is null, then the employee does not have a manager. No employee will
be the manager of themself.
Write an SQL query to report the managers with at least five direct reports.
Return the result table in any order. The query result format is in the
following example.
Example 1:
Input:
Employee table: +-----+-------+------------+-----------+
| id | name | department | managerId |
+-----+-------+------------+-----------+
| 101 | John | A | None |
| 102 | Dan | A | 101 |
| 103 | James | A | 101 |
| 104 | Amy | A | 101 |
| 105 | Anne | A | 101 |
| 106 | Ron | B | 101 |
+-----+-------+------------+-----------+
Output: +------+
| name |
+------+
| John |
+------+*/
SELECT Name
FROM Employee
WHERE Id IN
(SELECT ManagerId
FROM Employee
GROUP BY ManagerId
HAVING COUNT(ManagerId) >= 5)
/*574. Winning Candidate (Medium)
SQL Schema
Table: Candidate
+-------------+----------+
| Column Name | Type |
+-------------+----------+
| id | int |
| name | varchar |
+-------------+----------+
id is the primary key column for this table. Each row of this table contains
information about the id and the name of a candidate.
Table: Vote
+-------------+------+
| Column Name | Type |
+-------------+------+
| id | int |
| candidateId | int |
+-------------+------+
id is an auto-increment primary key. candidateId is a foreign key to id from
the Candidate table. Each row of this table determines the candidate who got
the ith vote in the elections.
Write an SQL query to report the name of the winning candidate (i.e., the
candidate who got the largest number of votes). The test cases are generated so
that exactly one candidate wins the elections. The query result format is in
the following example.
Example 1:
Input:
Candidate table: +----+------+
| id | name |
+----+------+
| 1 | A |
| 2 | B |
| 3 | C |
| 4 | D |
| 5 | E |
+----+------+
Vote table: +----+-------------+
| id | candidateId |
+----+-------------+
| 1 | 2 |
| 2 | 4 |
| 3 | 3 |
| 4 | 2 |
| 5 | 5 |
+----+-------------+
Output: +------+
| name |
+------+
| B |
+------+
Explanation: Candidate B has 2 votes. Candidates C, D, and E have 1 vote each.
The winner is candidate B.*/
SELECT Name
FROM
Candidate a,
(SELECT CandidateId
FROM Vote
GROUP BY CandidateId
ORDER BY COUNT(*) DESC
LIMIT 1) b
WHERE a.id = b.CandidateId;
/*578. Get Highest Answer Rate Question (Medium)
SQL Schema
Table: SurveyLog
+-------------+------+
| Column Name | Type |
+-------------+------+
| id | int |
| action | ENUM |
| question_id | int |
| answer_id | int |
| q_num | int |
| timestamp | int |
+-------------+------+
There is no primary key for this table. It may contain duplicates. action is an
ENUM of the type: "show", "answer", or "skip". Each row of this table indicates
the user with ID = id has taken an action with the question question_id at time
timestamp. If the action taken by the user is "answer", answer_id will contain
the id of that answer, otherwise, it will be null. q_num is the numeral order
of the question in the current session. The answer rate for a question is the
number of times a user answered the question by the number of times a user
showed the question.
Write an SQL query to report the question that has the highest answer rate. If
multiple questions have the same maximum answer rate, report the question with
the smallest question_id. The query result format is in the following example.
Example 1:
Input:
SurveyLog table: +----+--------+-------------+-----------+-------+-----------+
| id | action | question_id | answer_id | q_num | timestamp |
+----+--------+-------------+-----------+-------+-----------+
| 5 | show | 285 | null | 1 | 123 |
| 5 | answer | 285 | 124124 | 1 | 124 |
| 5 | show | 369 | null | 2 | 125 |
| 5 | skip | 369 | null | 2 | 126 |
+----+--------+-------------+-----------+-------+-----------+
Output: +------------+
| survey_log |
+------------+
| 285 |
+------------+
Explanation: Question 285 was showed 1 time and answered 1 time. The answer
rate of question 285 is 1.0. Question 369 was showed 1 time and
was not answered. The answer rate of question 369 is 0.0. Question
285 has the highest answer rate.*/
SELECT question_id AS survey_log
FROM survey_log
GROUP BY question_id
ORDER BY SUM(action="answer")/SUM(action="show") DESC
LIMIT 1;
/*580. Count Student Number in Departments (Medium)
SQL Schema
Table: Student
+--------------+---------+
| Column Name | Type |
+--------------+---------+
| student_id | int |
| student_name | varchar |
| gender | varchar |
| dept_id | int |
+--------------+---------+
student_id is the primary key column for this table. dept_id is a foreign key
to dept_id in the Department tables. Each row of this table indicates the name
of a student, their gender, and the id of their department.
Table: Department
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| dept_id | int |
| dept_name | varchar |
+-------------+---------+
dept_id is the primary key column for this table. Each row of this table
contains the id and the name of a department.
Write an SQL query to report the respective department name and number of
students majoring in each department for all departments in the Department
table (even ones with no current students). Return the result table ordered by
student_number in descending order. In case of a tie, order them by dept_name
alphabetically. The query result format is in the following example.
Example 1:
Input:
Student table: +------------+--------------+--------+---------+
| student_id | student_name | gender | dept_id |
+------------+--------------+--------+---------+
| 1 | Jack | M | 1 |
| 2 | Jane | F | 1 |
| 3 | Mark | M | 2 |
+------------+--------------+--------+---------+
Department table: +---------+-------------+
| dept_id | dept_name |
+---------+-------------+
| 1 | Engineering |
| 2 | Science |
| 3 | Law |
+---------+-------------+
Output: +-------------+----------------+
| dept_name | student_number |
+-------------+----------------+
| Engineering | 2 |
| Science | 1 |
| Law | 0 |
+-------------+----------------+*/
SELECT dept_name, IFNULL(student_number, 0) AS student_number
FROM
department a
LEFT JOIN (SELECT dept_id, COUNT(*) AS student_number FROM student GROUP BY dept_id) b
USING (dept_id)
ORDER BY student_number DESC, dept_name ASC
/*601. Human Traffic of Stadium (Hard)
Table: Stadium
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| visit_date | date |
| people | int |
+---------------+---------+
visit_date is the column with unique values for this table. Each row of this
table contains the visit date and visit id to the stadium with the number of
people during the visit. As the id increases, the date increases as well. Write
a solution to display the records with three or more rows with consecutive id's,
and the number of people is greater than or equal to 100 for each. Return the
result table ordered by visit_date in ascending order. The result format is in
the following example.
Example 1:
Input:
Stadium table:
+------+------------+-----------+
| id | visit_date | people |
+------+------------+-----------+
| 1 | 2017-01-01 | 10 |
| 2 | 2017-01-02 | 109 |
| 3 | 2017-01-03 | 150 |
| 4 | 2017-01-04 | 99 |
| 5 | 2017-01-05 | 145 |
| 6 | 2017-01-06 | 1455 |
| 7 | 2017-01-07 | 199 |
| 8 | 2017-01-09 | 188 |
+------+------------+-----------+
Output:
+------+------------+-----------+
| id | visit_date | people |
+------+------------+-----------+
| 5 | 2017-01-05 | 145 |
| 6 | 2017-01-06 | 1455 |
| 7 | 2017-01-07 | 199 |
| 8 | 2017-01-09 | 188 |
+------+------------+-----------+
Explanation:
* The four rows with ids 5, 6, 7, and 8 have consecutive ids and each of them
has >= 100 people attended. Note that row 8 was included even though the
visit_date was not the next day after row 7.
* The rows with ids 2 and 3 are not included because we need at least three
consecutive ids.
*/
WITH cte AS (
SELECT
*,
id - ROW_NUMBER() OVER (ORDER by id) AS diff
FROM Stadium
WHERE people >= 100
)
SELECT
id,
visit_date,
people
FROM cte
WHERE diff IN
(SELECT diff
FROM cte
GROUP BY diff
HAVING COUNT(*) >= 3)
ORDER BY 2;
/*602. Friend Requests II: Who Has the Most Friends (Medium)
SQL Schema
Table: RequestAccepted
+----------------+---------+
| Column Name | Type |
+----------------+---------+
| requester_id | int |
| accepter_id | int |
| accept_date | date |
+----------------+---------+
(requester_id, accepter_id) is the primary key for this table. This table
contains the ID of the user who sent the request, the ID of the user who
received the request, and the date when the request was accepted.
Write an SQL query to find the people who have the most friends and the most
friends number. The test cases are generated so that only one person has the
most friends. The query result format is in the following example.
Example 1:
Input:
RequestAccepted table: +--------------+-------------+-------------+
| requester_id | accepter_id | accept_date |
+--------------+-------------+-------------+
| 1 | 2 | 2016/06/03 |
| 1 | 3 | 2016/06/08 |
| 2 | 3 | 2016/06/08 |
| 3 | 4 | 2016/06/09 |
+--------------+-------------+-------------+
Output: +----+-----+
| id | num |
+----+-----+
| 3 | 3 |
+----+-----+
Explanation: The person with id 3 is a friend of people 1, 2, and 4, so he has
three friends in total, which is the most number than any others.
Follow up: In the real world, multiple people could have the same most number
of friends. Could you find all these people in this case?*/
SELECT
id,
COUNT(*) AS num
FROM (SELECT requester_id AS id FROM request_accepted
UNION ALL
SELECT accepter_id AS id FROM request_accepted) a
GROUP BY id
ORDER BY num DESC
LIMIT 1
/*608. Tree Node (Medium)
SQL Schema
Table: Tree
+-------------+------+
| Column Name | Type |
+-------------+------+
| id | int |
| p_id | int |
+-------------+------+
id is the primary key column for this table. Each row of this table contains
information about the id of a node and the id of its parent node in a tree. The
given structure is always a valid tree. Each node in the tree can be one of
three types:
* "Leaf": if the node is a leaf node.
* "Root": if the node is the root of the tree.
* "Inner": If the node is neither a leaf node nor a root node.
Write an SQL query to report the type of each node in the tree. Return the
result table ordered by id in ascending order. The query result format is in
the following example.
Example 1:
Input:
Tree table: +----+------+
| id | p_id |
+----+------+
| 1 | null |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 2 |
+----+------+
Output: +----+-------+
| id | type |
+----+-------+
| 1 | Root |
| 2 | Inner |
| 3 | Leaf |
| 4 | Leaf |
| 5 | Leaf |
+----+-------+
Explanation: Node 1 is the root node because its parent node is null and it has
child nodes 2 and 3. Node 2 is an inner node because it has parent
node 1 and child node 4 and 5. Nodes 3, 4, and 5 are leaf nodes
because they have parent nodes and they do not have child nodes.
Example 2:
Input:
Tree table: +----+------+
| id | p_id |
+----+------+
| 1 | null |
+----+------+
Output: +----+-------+
| id | type |
+----+-------+
| 1 | Root |
+----+-------+
Explanation: If there is only one node on the tree, you only need to output its
root attributes.*/
SELECT
id,
CASE WHEN p_id IS NULL THEN "Root"
WHEN id NOT IN (SELECT IFNULL(p_id, 0) FROM tree) THEN "Leaf"
ELSE "Inner" END AS Type
FROM tree
ORDER BY id
/*612. Shortest Distance in a Plane (Medium)
SQL Schema
Table: Point2D
+-------------+------+
| Column Name | Type |
+-------------+------+
| x | int |
| y | int |
+-------------+------+
(x, y) is the primary key column for this table. Each row of this table
indicates the position of a point on the X-Y plane. The distance between two
points p1(x1, y1) and p2(x2, y2) is sqrt((x2 - x1)2 + (y2 - y1)2).
Write an SQL query to report the shortest distance between any two points from
the Point2D table. Round the distance to two decimal points. The query result
format is in the following example.
Example 1:
Input:
Point2D table: +----+----+
| x | y |
+----+----+
| -1 | -1 |
| 0 | 0 |
| -1 | -2 |
+----+----+
Output: +----------+
| shortest |
+----------+
| 1.00 |
+----------+
Explanation: The shortest distance is 1.00 from point (-1, -1) to (-1, 2).*/
SELECT ROUND(SQRT(MIN(POWER(a.x-b.x, 2) + POWER(a.y-b.y, 2))), 2) AS shortest
FROM point_2d a
JOIN point_2d b ON NOT (a.x = b.x AND a.y = b.y)
/*614. Second Degree Follower (Medium)
SQL Schema
Table: Follow
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| followee | varchar |
| follower | varchar |
+-------------+---------+
(followee, follower) is the primary key column for this table. Each row of this
table indicates that the user follower follows the user followee on a social
network. There will not be a user following themself. A second-degree follower
is a user who:
* follows at least one user, and
* is followed by at least one user.
Write an SQL query to report the second-degree users and the number of their
followers. Return the result table ordered by follower in alphabetical order.
The query result format is in the following example.
Example 1:
Input:
Follow table: +----------+----------+
| followee | follower |
+----------+----------+
| Alice | Bob |
| Bob | Cena |
| Bob | Donald |
| Donald | Edward |
+----------+----------+
Output: +----------+-----+
| follower | num |
+----------+-----+
| Bob | 2 |
| Donald | 1 |
+----------+-----+
Explanation: User Bob has 2 followers. Bob is a second-degree follower because
he follows Alice, so we include him in the result table. User
Donald has 1 follower. Donald is a second-degree follower because
he follows Bob, so we include him in the result table. User Alice
has 1 follower. Alice is not a second-degree follower because she
does not follow anyone, so we don not include her in the result
table.*/
SELECT
followee AS follower,
COUNT(DISTINCT follower) AS num
FROM follow
WHERE followee IN (SELECT follower FROM follow)
GROUP BY followee
ORDER BY followee
/*626. Exchange Seats (Medium)
SQL Schema
Table: Seat
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| student | varchar |
+-------------+---------+
id is the primary key column for this table. Each row of this table indicates
the name and the ID of a student. id is a continuous increment.
Write an SQL query to swap the seat id of every two consecutive students. If
the number of students is odd, the id of the last student is not swapped.
Return the result table ordered by id in ascending order. The query result
format is in the following example.
Example 1:
Input:
Seat table: +----+---------+
| id | student |
+----+---------+
| 1 | Abbot |
| 2 | Doris |
| 3 | Emerson |
| 4 | Green |
| 5 | Jeames |
+----+---------+
Output: +----+---------+
| id | student |
+----+---------+
| 1 | Doris |
| 2 | Abbot |
| 3 | Green |
| 4 | Emerson |
| 5 | Jeames |
+----+---------+
Explanation: Note that if the number of students is odd, there is no need to
change the last one's seat.*/
SELECT
CASE WHEN MOD(id, 2) AND id = (SELECT COUNT(*) FROM seat) THEN id
ELSE (id+1)^1-1
END AS id, student
FROM
seat
ORDER BY id
/*1045. Customers Who Bought All Products (Medium)
SQL Schema
Table: Customer
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| customer_id | int |
| product_key | int |
+-------------+---------+
There is no primary key for this table. It may contain duplicates. product_key
is a foreign key to Product table.
Table: Product
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| product_key | int |
+-------------+---------+
product_key is the primary key column for this table.
Write an SQL query to report the customer ids from the Customer table that
bought all the products in the Product table. Return the result table in any
order. The query result format is in the following example.
Example 1:
Input:
Customer table: +-------------+-------------+
| customer_id | product_key |
+-------------+-------------+
| 1 | 5 |
| 2 | 6 |
| 3 | 5 |
| 3 | 6 |
| 1 | 6 |
+-------------+-------------+
Product table: +-------------+
| product_key |
+-------------+
| 5 |
| 6 |
+-------------+
Output: +-------------+
| customer_id |
+-------------+
| 1 |
| 3 |
+-------------+
Explanation: The customers who bought all the products (5 and 6) are customers
with IDs 1 and 3.*/
SELECT customer_id
FROM Customer
GROUP BY customer_id
HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product)
/*1070. Product Sales Analysis III (Medium)
SQL Schema
Table: Sales
+-------------+-------+
| Column Name | Type |
+-------------+-------+
| sale_id | int |
| product_id | int |
| year | int |
| quantity | int |
| price | int |
+-------------+-------+
(sale_id, year) is the primary key of this table. product_id is a foreign key
to Product table. Each row of this table shows a sale on the product product_id
in a certain year. Note that the price is per unit.