diff --git a/CustomersWithStrictlyIncreasingPurchases.sql b/CustomersWithStrictlyIncreasingPurchases.sql new file mode 100644 index 0000000..77c8faf --- /dev/null +++ b/CustomersWithStrictlyIncreasingPurchases.sql @@ -0,0 +1,16 @@ +WITH cte AS ( + SELECT customer_id, + YEAR(order_date) AS year, + SUM(price) AS price + FROM orders + GROUP BY 1,2 + ORDER BY 1,2 +) +SELECT DISTINCT c1.customer_id +FROM cte c1 +LEFT JOIN cte c2 +ON (c1.customer_id = c2.customer_id +AND c1.year + 1 = c2.year +AND c2.price > c1.price) +GROUP BY 1 +HAVING COUNT(c1.customer_id) - COUNT(c2.customer_id) = 1; \ No newline at end of file diff --git a/ShortestDistanceInaPlane.sql b/ShortestDistanceInaPlane.sql new file mode 100644 index 0000000..6b4f343 --- /dev/null +++ b/ShortestDistanceInaPlane.sql @@ -0,0 +1,8 @@ +-- Solution for Leetcode problem ShortestDistanceInaPlane +SELECT MIN(ROUND(SQRT(POW(p1.x - p2.x, 2) + POW(p1.y - p2.y, 2)), 2)) AS shortest +FROM point2d p1 +JOIN point2d p2 +ON p1.x < p2.x OR p1.y < p2.y +/*we can also use the following*/ +-- ON (p1.x,p1.y) < (p2.x,p2.y) +; \ No newline at end of file diff --git a/combine_two_tables b/combine_two_tables new file mode 100644 index 0000000..4d04a0f --- /dev/null +++ b/combine_two_tables @@ -0,0 +1,7 @@ +SELECT p.firstname, + p.lastname, + a.city, + a.state +FROM person p +LEFT JOIN address a +ON p.personid = a.personid; \ No newline at end of file diff --git a/game_analysis_2 b/game_analysis_2 new file mode 100644 index 0000000..d0225ac --- /dev/null +++ b/game_analysis_2 @@ -0,0 +1,28 @@ +-- Method 1 +WITH cte AS ( + SELECT player_id, + MIN(event_date) AS first_login + FROM activity + GROUP BY player_id +) +SELECT a.player_id, + a.device_id +FROM activity a +JOIN cte c +ON a.player_id = c.player_id AND a.event_date = c.first_login; + +-- Method 2 +SELECT DISTINCT player_id, + FIRST_VALUE(device_id) OVER(PARTITION BY player_id ORDER BY event_date RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) device_id +FROM activity; + +-- Method 3 +SELECT player_id, + device_id +FROM ( + SELECT player_id, + device_id, + DENSE_RANK() OVER(PARTITION BY player_id ORDER BY event_date) rnk + FROM activity +)a +WHERE rnk = 1; \ No newline at end of file diff --git a/game_play_analysis_3 b/game_play_analysis_3 new file mode 100644 index 0000000..ce8c7b9 --- /dev/null +++ b/game_play_analysis_3 @@ -0,0 +1,14 @@ +-- Method 1 +SELECT player_id, + event_date, + SUM(games_played) OVER(PARTITION BY player_id ORDER BY event_date) AS games_played_so_far +FROM activity; + +-- Method 2 +SELECT a1.player_id, + a1.event_date, + (SELECT SUM(a2.games_played) + FROM activity a2 + WHERE a1.player_id = a2.player_id + AND a2.event_date <= a1.event_date) AS games_played_so_far +FROm activity a1; \ No newline at end of file