|
| 1 | +-- Table: Users |
| 2 | + |
| 3 | +-- +---------------+---------+ |
| 4 | +-- | Column Name | Type | |
| 5 | +-- +---------------+---------+ |
| 6 | +-- | id | int | |
| 7 | +-- | name | varchar | |
| 8 | +-- +---------------+---------+ |
| 9 | +-- id is the primary key for this table. |
| 10 | +-- name is the name of the user. |
| 11 | + |
| 12 | + |
| 13 | +-- Table: Rides |
| 14 | + |
| 15 | +-- +---------------+---------+ |
| 16 | +-- | Column Name | Type | |
| 17 | +-- +---------------+---------+ |
| 18 | +-- | id | int | |
| 19 | +-- | user_id | int | |
| 20 | +-- | distance | int | |
| 21 | +-- +---------------+---------+ |
| 22 | +-- id is the primary key for this table. |
| 23 | +-- user_id is the id of the user who travelled the distance "distance". |
| 24 | + |
| 25 | + |
| 26 | +-- Write an SQL query to report the distance travelled by each user. |
| 27 | + |
| 28 | +-- Return the result table ordered by travelled_distance in descending order, if two or more users travelled the same distance, order them by their name in ascending order. |
| 29 | + |
| 30 | +-- The query result format is in the following example. |
| 31 | + |
| 32 | + |
| 33 | + |
| 34 | +-- Users table: |
| 35 | +-- +------+-----------+ |
| 36 | +-- | id | name | |
| 37 | +-- +------+-----------+ |
| 38 | +-- | 1 | Alice | |
| 39 | +-- | 2 | Bob | |
| 40 | +-- | 3 | Alex | |
| 41 | +-- | 4 | Donald | |
| 42 | +-- | 7 | Lee | |
| 43 | +-- | 13 | Jonathan | |
| 44 | +-- | 19 | Elvis | |
| 45 | +-- +------+-----------+ |
| 46 | + |
| 47 | +-- Rides table: |
| 48 | +-- +------+----------+----------+ |
| 49 | +-- | id | user_id | distance | |
| 50 | +-- +------+----------+----------+ |
| 51 | +-- | 1 | 1 | 120 | |
| 52 | +-- | 2 | 2 | 317 | |
| 53 | +-- | 3 | 3 | 222 | |
| 54 | +-- | 4 | 7 | 100 | |
| 55 | +-- | 5 | 13 | 312 | |
| 56 | +-- | 6 | 19 | 50 | |
| 57 | +-- | 7 | 7 | 120 | |
| 58 | +-- | 8 | 19 | 400 | |
| 59 | +-- | 9 | 7 | 230 | |
| 60 | +-- +------+----------+----------+ |
| 61 | + |
| 62 | +-- Result table: |
| 63 | +-- +----------+--------------------+ |
| 64 | +-- | name | travelled_distance | |
| 65 | +-- +----------+--------------------+ |
| 66 | +-- | Elvis | 450 | |
| 67 | +-- | Lee | 450 | |
| 68 | +-- | Bob | 317 | |
| 69 | +-- | Jonathan | 312 | |
| 70 | +-- | Alex | 222 | |
| 71 | +-- | Alice | 120 | |
| 72 | +-- | Donald | 0 | |
| 73 | +-- +----------+--------------------+ |
| 74 | +-- Elvis and Lee travelled 450 miles, Elvis is the top traveller as his name is alphabetically smaller than Lee. |
| 75 | +-- Bob, Jonathan, Alex and Alice have only one ride and we just order them by the total distances of the ride. |
| 76 | +-- Donald didn't have any rides, the distance travelled by him is 0. |
| 77 | + |
| 78 | +-- Solution |
1 | 79 | Select U.name as name, coalesce(sum(R.distance),0) as travelled_distance
|
2 | 80 | from Users U left join Rides R
|
3 | 81 | on R.user_id = U.id
|
|
0 commit comments