|
| 1 | +-- Question 109 |
| 2 | +-- Table: UserActivity |
| 3 | + |
| 4 | +-- +---------------+---------+ |
| 5 | +-- | Column Name | Type | |
| 6 | +-- +---------------+---------+ |
| 7 | +-- | username | varchar | |
| 8 | +-- | activity | varchar | |
| 9 | +-- | startDate | Date | |
| 10 | +-- | endDate | Date | |
| 11 | +-- +---------------+---------+ |
| 12 | +-- This table does not contain primary key. |
| 13 | +-- This table contain information about the activity performed of each user in a period of time. |
| 14 | +-- A person with username performed a activity from startDate to endDate. |
| 15 | + |
| 16 | +-- Write an SQL query to show the second most recent activity of each user. |
| 17 | + |
| 18 | +-- If the user only has one activity, return that one. |
| 19 | + |
| 20 | +-- A user can't perform more than one activity at the same time. Return the result table in any order. |
| 21 | + |
| 22 | +-- The query result format is in the following example: |
| 23 | + |
| 24 | +-- UserActivity table: |
| 25 | +-- +------------+--------------+-------------+-------------+ |
| 26 | +-- | username | activity | startDate | endDate | |
| 27 | +-- +------------+--------------+-------------+-------------+ |
| 28 | +-- | Alice | Travel | 2020-02-12 | 2020-02-20 | |
| 29 | +-- | Alice | Dancing | 2020-02-21 | 2020-02-23 | |
| 30 | +-- | Alice | Travel | 2020-02-24 | 2020-02-28 | |
| 31 | +-- | Bob | Travel | 2020-02-11 | 2020-02-18 | |
| 32 | +-- +------------+--------------+-------------+-------------+ |
| 33 | + |
| 34 | +-- Result table: |
| 35 | +-- +------------+--------------+-------------+-------------+ |
| 36 | +-- | username | activity | startDate | endDate | |
| 37 | +-- +------------+--------------+-------------+-------------+ |
| 38 | +-- | Alice | Dancing | 2020-02-21 | 2020-02-23 | |
| 39 | +-- | Bob | Travel | 2020-02-11 | 2020-02-18 | |
| 40 | +-- +------------+--------------+-------------+-------------+ |
| 41 | + |
| 42 | +-- The most recent activity of Alice is Travel from 2020-02-24 to 2020-02-28, before that she was dancing from 2020-02-21 to 2020-02-23. |
| 43 | +-- Bob only has one record, we just take that one. |
| 44 | + |
| 45 | +-- Solution |
| 46 | +select username, activity, startdate, enddate |
| 47 | +from |
| 48 | +(select *, |
| 49 | +rank() over(partition by username order by startdate desc) as rk, |
| 50 | +count(username) over(partition by username) as cnt |
| 51 | +from useractivity) a |
| 52 | +where a.rk = 2 or cnt = 1 |
0 commit comments