diff --git a/problem1-178-rank-scores.sql b/problem1-178-rank-scores.sql new file mode 100644 index 0000000..7c6c8d6 --- /dev/null +++ b/problem1-178-rank-scores.sql @@ -0,0 +1,5 @@ +select +score, +dense_rank() over(order by score desc) AS `rank` +from +Scores \ No newline at end of file diff --git a/problem2-626-exchange-seats.sql b/problem2-626-exchange-seats.sql new file mode 100644 index 0000000..e6a635c --- /dev/null +++ b/problem2-626-exchange-seats.sql @@ -0,0 +1,44 @@ +--case statement +select + case + when id%2=1 and id < (select max(id) from seat) then id + 1 + when id%2=0 then id-1 + else + id + END AS id, + student +from + seat +order by id + +--self join +SELECT + s1.id, + COALESCE(s2.student, s1.student) AS student +FROM Seat s1 +LEFT JOIN Seat s2 + ON ( + (s1.id % 2 = 1 AND s2.id = s1.id + 1) OR + (s1.id % 2 = 0 AND s2.id = s1.id - 1) + ) +ORDER BY s1.id; + +--window function lead,lag +SELECT + id, + case + when id%2=1 and id < (select max(id) from seat) then lead(student) over(order by id) + when id%2=0 then lag(student) over(order by id) + else student + END as student +FROM Seat +ORDER BY id + +--bitwise operator +SELECT + s1.id, + coalesce(s2.student,s1.student) as student +FROM Seat s1 +left join Seat s2 +on (s1.id +1)^1-1=s2.id +ORDER BY id diff --git a/problem3-608-tree-nodes.sql b/problem3-608-tree-nodes.sql new file mode 100644 index 0000000..2028b1b --- /dev/null +++ b/problem3-608-tree-nodes.sql @@ -0,0 +1,39 @@ +--case statement +SELECT + id, + CASE + WHEN p_id IS NULL THEN 'Root' + WHEN id NOT IN (SELECT DISTINCT p_id FROM Tree WHERE p_id IS NOT NULL) then 'Leaf' + ELSE 'Inner' + END AS type +FROM Tree; + +--if condition +SELECT + id, + IF(P_id is null,'Root',IF(id not in (select distinct p_id from Tree where p_id is not null),'Leaf','Inner')) AS type +FROM Tree; + +--union + +SELECT + id, + 'Root' AS type +FROM Tree +where p_id is null + +union + +SELECT + id, + 'Leaf' AS type +FROM Tree +where id not in (select distinct p_id from Tree where p_id is not null) and p_id is not null + +union + +SELECT + id, + 'Inner' AS type +FROM Tree +where id in (select distinct p_id from Tree) and p_id is not null \ No newline at end of file