-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path2238. Number of Times a Driver Was a Passenger.py
86 lines (52 loc) · 1.62 KB
/
2238. Number of Times a Driver Was a Passenger.py
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
2238. Number of Times a Driver Was a Passenger
Medium
25
2
Add to List
Share
SQL Schema
Table: Rides
+--------------+------+
| Column Name | Type |
+--------------+------+
| ride_id | int |
| driver_id | int |
| passenger_id | int |
+--------------+------+
ride_id is the primary key for this table.
Each row of this table contains the ID of the driver and the ID of the passenger that rode in ride_id.
Note that driver_id != passenger_id.
Write an SQL query to report the ID of each driver and the number of times they were a passenger.
Return the result table in any order.
The query result format is in the following example.
Example 1:
Input:
Rides table:
+---------+-----------+--------------+
| ride_id | driver_id | passenger_id |
+---------+-----------+--------------+
| 1 | 7 | 1 |
| 2 | 7 | 2 |
| 3 | 11 | 1 |
| 4 | 11 | 7 |
| 5 | 11 | 7 |
| 6 | 11 | 3 |
+---------+-----------+--------------+
Output:
+-----------+-----+
| driver_id | cnt |
+-----------+-----+
| 7 | 2 |
| 11 | 0 |
+-----------+-----+
Explanation:
There are two drivers in all the given rides: 7 and 11.
The driver with ID = 7 was a passenger two times.
The driver with ID = 11 was never a passenger.
/* Write your T-SQL query statement below */
/* Write your T-SQL query statement below */
select a.driver_id, count(r.passenger_id) as cnt
from
(select driver_id from Rides group by driver_id)a
left join Rides r on a.driver_id = r.passenger_id
group by a.driver_id