Assignment Solutions: Basic SQL 1
Categories
Take a look at the solutions and explanations to the Assignment: Basic SQL 1.
Hope you had fun solving the Basic SQL 1 questions and that they were not too difficult. Now we’ll go through every concept tested in the assignment, show you the solutions, and explain them.
Filtering Data Using One Condition in WHERE
The WHERE clause in SQL is used for filtering data before the aggregation. The query will return all the records that satisfy the condition stated in the WHERE clause.
These are the operators you can use in WHERE:
Operator | Meaning |
= | Equals |
< | Less than |
> | Greater than |
<= | Less than or equal |
>= | Greater than or equal |
<> | Does not equal |
BETWEEN | Between the specified range |
LIKE | Looking for a pattern |
IN | Equals the values listed in the parentheses |
Note that the WHERE clause in PostgreSQL is case-sensitive.
Question 1
Find all inspections which are part of an inactive program
“Find all inspections which are part of an inactive program.”
Link to the question: https://platform.stratascratch.com/coding/10277-find-all-inspections-which-are-part-of-an-inactive-program
Data
The data you have here is in the table los_angeles_restaurant_health_inspections.
serial_number | activity_date | facility_name | score | grade | service_code | service_description | employee_id | facility_address | facility_city | facility_id | facility_state | facility_zip | owner_id | owner_name | pe_description | program_element_pe | program_name | program_status | record_id |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
DAQHRSETQ | 2017-06-08 | MARGARITAS CAFE | 93 | A | 1 | ROUTINE INSPECTION | EE0000006 | 5026 S CRENSHAW BLVD | LOS ANGELES | FA0023656 | CA | 90043 | OW0004133 | BAZAN, ASCENCION | RESTAURANT (61-150) SEATS HIGH RISK | 1638 | MARGARITAS CAFE | ACTIVE | PR0011718 |
DA2GQRJOS | 2017-03-07 | LAS MOLENDERAS | 97 | A | 1 | ROUTINE INSPECTION | EE0000997 | 2635 WHITTIER BLVD | LOS ANGELES | FA0160416 | CA | 90023 | OW0125379 | MARISOL FEREGRINO | RESTAURANT (0-30) SEATS HIGH RISK | 1632 | LAS MOLENDERAS | INACTIVE | PR0148504 |
DAMQTA46T | 2016-03-22 | SANDRA'S TAMALES | 93 | A | 1 | ROUTINE INSPECTION | EE0001049 | 5390 WHITTIER BLVD | LOS ANGELES | FA0171769 | CA | 90022-4032 | OW0178828 | SANDRA'S TAMALES INC. | RESTAURANT (0-30) SEATS MODERATE RISK | 1631 | SANDRA'S TAMALES | ACTIVE | PR0164225 |
DAXMBTIRZ | 2018-02-12 | CAFE GRATITUDE | 97 | A | 1 | ROUTINE INSPECTION | EE0000828 | 639 N LARCHMONT BLVD STE #102 | LOS ANGELES | FA0058921 | CA | 90004 | OW0005704 | CAFE GRATITUDE LARCHMONT LLC | RESTAURANT (61-150) SEATS HIGH RISK | 1638 | CAFE GRATITUDE | ACTIVE | PR0019854 |
DAK8TBMS0 | 2015-09-10 | THE WAFFLE | 90 | A | 1 | ROUTINE INSPECTION | EE0000709 | 6255 W SUNSET BLVD STE #105 | LOS ANGELES | FA0051830 | CA | 90028 | OW0035796 | THE WAFFLE, LLC | RESTAURANT (61-150) SEATS HIGH RISK | 1638 | THE WAFFLE | ACTIVE | PR0010922 |
Solution
To write the solution, you need to select all the columns from the table and filter the output by the column program_status.
SELECT *
FROM los_angeles_restaurant_health_inspections
WHERE program_status = 'INACTIVE';
Use the WHERE clause to show only data with the inactive program status. Since the WHERE clause is case-sensitive, the status name has to be written in all capitalized. That’s how it’s recorded in the source table.
You should get this output by running the code.
serial_number | activity_date | facility_name | score | grade | service_code | service_description | employee_id | facility_address | facility_city | facility_id | facility_state | facility_zip | owner_id | owner_name | pe_description | program_element_pe | program_name | program_status | record_id |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
DA2GQRJOS | 2017-03-07 | LAS MOLENDERAS | 97 | A | 1 | ROUTINE INSPECTION | EE0000997 | 2635 WHITTIER BLVD | LOS ANGELES | FA0160416 | CA | 90023 | OW0125379 | MARISOL FEREGRINO | RESTAURANT (0-30) SEATS HIGH RISK | 1632 | LAS MOLENDERAS | INACTIVE | PR0148504 |
DAQZAULOI | 2017-10-11 | INTI PERUVIAN RESTAURANT | 94 | A | 1 | ROUTINE INSPECTION | EE0000828 | 5870 MELROSE AVE # #105 | LOS ANGELES | FA0030334 | CA | 90038 | OW0023369 | MARIN & MARTINEZ GROUP CORP. | RESTAURANT (31-60) SEATS HIGH RISK | 1635 | INTI PERUVIAN RESTAURANT | INACTIVE | PR0043182 |
DA0N7AWN0 | 2016-09-21 | MICHELLE'S DONUT HOUSE | 96 | A | 1 | ROUTINE INSPECTION | EE0000798 | 3783 S WESTERN AVE | LOS ANGELES | FA0039310 | CA | 90018 | OW0032004 | SCOTT VICHETH KHEM | RESTAURANT (0-30) SEATS MODERATE RISK | 1631 | MICHELLE'S DONUT HOUSE | INACTIVE | PR0031269 |
DA2M0ZPRD | 2017-01-24 | LA PRINCESITA MARKET | 95 | A | 1 | ROUTINE INSPECTION | EE0000997 | 2426 E 4TH ST | LOS ANGELES | FA0065292 | CA | 90063 | OW0029496 | RAMIREZ FRANCISCO | FOOD MKT RETAIL (25-1,999 SF) HIGH RISK | 1612 | LA PRINCESITA MARKET | INACTIVE | PR0027280 |
DAKIPC9UB | 2016-06-16 | LA PETITE BOULANGERIE | 86 | B | 1 | ROUTINE INSPECTION | EE0000721 | 330 S HOPE ST | LOS ANGELES | FA0180531 | CA | 90071 | OW0185889 | MARCO INVESTMENT CORP. | RESTAURANT (31-60) SEATS MODERATE RISK | 1634 | LA PETITE BOULANGERIE | INACTIVE | PR0174307 |
Finding the Unique Values and Filtering Data Using More Than One Condition in WHERE
The DISTINCT statement returns only the unique values from the table. In other words, the duplicate rows will appear only once.
When there’s a need to filter data on more than one criteria, the keyword that needs to be used is AND.
State the first criteria in the WHERE clause, then write AND to write the second criteria, and so on. You’ll get a chain of criteria separated by the AND keyword. Note that you write WHERE only once.
Also, apart from using the AND operator for filtering on two or more criteria, you can use OR and NOT operators.
Question 2
London Olympic Swimmers
“Find the athletes who competed in swimming events at the London Olympics.”
Link to the question: https://platform.stratascratch.com/coding/9934-london-olympic-swimmers
Data
The question gives you the table olympics_athletes_events to work with.
id | name | sex | age | height | weight | team | noc | games | year | season | city | sport | event | medal |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3520 | Guillermo J. Amparan | M | Mexico | MEX | 1924 Summer | 1924 | Summer | Paris | Athletics | Athletics Men's 800 metres | ||||
35394 | Henry John Finchett | M | Great Britain | GBR | 1924 Summer | 1924 | Summer | Paris | Gymnastics | Gymnastics Men's Rings | ||||
21918 | Georg Frederik Ahrensborg Clausen | M | 28 | Denmark | DEN | 1924 Summer | 1924 | Summer | Paris | Cycling | Cycling Men's Road Race Individual | |||
110345 | Marinus Cornelis Dick Sigmond | M | 26 | Netherlands | NED | 1924 Summer | 1924 | Summer | Paris | Football | Football Men's Football | |||
54193 | Thodore Tho Jeitz | M | 26 | Luxembourg | LUX | 1924 Summer | 1924 | Summer | Paris | Gymnastics | Gymnastics Men's Individual All-Around |
Solution
The athletes can compete more than once in the Olympics, so it’s wise to assume the athletes are showing more than once in the table. Use DISTINCT to show the athletes only once.
The output has to be filtered to show only swimming events, and the city should be London.
SELECT DISTINCT name
FROM olympics_athletes_events
WHERE sport = 'Swimming'
AND city = 'London';
Run the code to get the output.
name |
---|
Jeong Won-Yong |
Leslie George Rich |
Samuel Sam Blatherwick |
Theodora Drakou |
Filtering Out the NULL Values and Sorting Data
The output will not show the NULL values when the column specified in the WHERE clause is followed by ‘IS NOT NULL’.
If you want to show only the NULL values, then you have to write ‘IS NULL’.
The code output is sorted using the ORDER BY clause, where you explicitly state the column to be used for ordering data. After the column name, use the ASC keyword to sort data in ascending order. For descending order, use the keyword DESC.
It’s also possible to sort data by more than one column. To do that, simply separate the columns in the ORDER BY clause with a comma.
Question 3
Find all searches for San Francisco with a flexible cancellation policy and a review score rating
“Find all searches for San Francisco with a flexible cancellation policy and a review score rating. Sort the results by the review score in the descending order.”
Link to the question: https://platform.stratascratch.com/coding/9621-find-all-searches-for-san-francisco-with-a-flexible-cancellation-policy-and-a-review-score-rating
Data
There’s again one table: airbnb_search_details.
id | price | property_type | room_type | amenities | accommodates | bathrooms | bed_type | cancellation_policy | cleaning_fee | city | host_identity_verified | host_response_rate | host_since | neighbourhood | number_of_reviews | review_scores_rating | zipcode | bedrooms | beds |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
12513361 | 555.68 | Apartment | Entire home/apt | {TV,"Wireless Internet","Air conditioning","Smoke detector","Carbon monoxide detector",Essentials,"Lock on bedroom door",Hangers,Iron} | 2 | 1 | Real Bed | flexible | FALSE | NYC | t | 89% | 2015-11-18 | East Harlem | 3 | 87 | 10029 | 0 | 1 |
7196412 | 366.36 | Cabin | Private room | {"Wireless Internet",Kitchen,Washer,Dryer,"Smoke detector","First aid kit","Fire extinguisher",Essentials,"Hair dryer","translation missing: en.hosting_amenity_49","translation missing: en.hosting_amenity_50"} | 2 | 3 | Real Bed | moderate | FALSE | LA | f | 100% | 2016-09-10 | Valley Glen | 14 | 91 | 91606 | 1 | 1 |
16333776 | 482.83 | House | Private room | {TV,"Cable TV",Internet,"Wireless Internet",Kitchen,"Free parking on premises","Pets live on this property",Dog(s),"Indoor fireplace","Buzzer/wireless intercom",Heating,Washer,Dryer,"Smoke detector","Carbon monoxide detector","First aid kit","Safety card","Fire extinguisher",Essentials,Shampoo,"24-hour check-in",Hangers,"Hair dryer",Iron,"Laptop friendly workspace","translation missing: en.hosting_amenity_49","translation missing: en.hosting_amenity_50","Self Check-In",Lockbox} | 2 | 1 | Real Bed | strict | TRUE | SF | t | 100% | 2013-12-26 | Richmond District | 117 | 96 | 94118 | 1 | 1 |
1786412 | 448.86 | Apartment | Private room | {"Wireless Internet","Air conditioning",Kitchen,Heating,"Suitable for events","Smoke detector","Carbon monoxide detector","First aid kit","Fire extinguisher",Essentials,Shampoo,"Lock on bedroom door",Hangers,"translation missing: en.hosting_amenity_49","translation missing: en.hosting_amenity_50"} | 2 | 1 | Real Bed | strict | TRUE | NYC | t | 93% | 2010-05-11 | Williamsburg | 8 | 86 | 11211 | 1 | 1 |
14575777 | 506.89 | Villa | Private room | {TV,Internet,"Wireless Internet","Air conditioning",Kitchen,"Free parking on premises",Essentials,Shampoo,"translation missing: en.hosting_amenity_49","translation missing: en.hosting_amenity_50"} | 6 | 2 | Real Bed | strict | TRUE | LA | t | 70% | 2015-10-22 | 2 | 100 | 90703 | 3 | 3 |
Solution
You need to show all the columns in the SELECT statement.
There will be three filtering criteria in the WHERE clause: the city is San Francisco, the cancellation policy is flexible, and there has to be a review score rating.
When looking for data that is not NULL. The command that will return non-NULL values is ‘IS NOT NULL’.
Finally, the output has to be in descending order according to the review scores rating.
SELECT *
FROM airbnb_search_details
WHERE city='SF'
AND cancellation_policy='flexible'
AND review_scores_rating IS NOT NULL
ORDER BY review_scores_rating DESC;
The result is only one row.
id | price | property_type | room_type | amenities | accommodates | bathrooms | bed_type | cancellation_policy | cleaning_fee | city | host_identity_verified | host_response_rate | host_since | neighbourhood | number_of_reviews | review_scores_rating | zipcode | bedrooms | beds |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
13276443 | 470.05 | House | Private room | {"Cable TV",Internet,"Wireless Internet","Air conditioning",Kitchen,"Indoor fireplace",Washer,"Smoke detector","Carbon monoxide detector","First aid kit",Shampoo} | 2 | 1 | Real Bed | flexible | FALSE | SF | t | 2013-05-15 | Russian Hill | 2 | 100 | 94109 | 1 | 1 |
Using LIMIT to Filter Data
One way of filtering data in the output is using the LIMIT keyword. Unlike the WHERE clause, LIMIT doesn’t filter data based on its value.
The purpose of LIMIT is to limit the output to a certain number of rows.
Question 4
Hour Of Highest Gas Expense
“Find the hour with the highest gasoline cost. Assume there's only 1 hour with the highest gas cost.”
Link to the question: https://platform.stratascratch.com/coding/10005-hour-of-highest-gas-expense
Data
The table is lyft_rides with five columns.
index | weather | hour | travel_distance | gasoline_cost |
---|---|---|---|---|
0 | cloudy | 7 | 24.47 | 1.13 |
1 | cloudy | 23 | 23.67 | 1.99 |
2 | sunny | 17 | 20.93 | 0.86 |
3 | rainy | 2 | 29.58 | 0.85 |
4 | rainy | 7 | 16.11 | 0.95 |
Solution
The query will select only the column hour from the table. If data is ordered by the gasoline cost in descending order, the output will show hours sorted from the highest to the lowest gas price.
To show only the highest price, you need to show one row and there it is.
SELECT hour
FROM lyft_rides
ORDER BY gasoline_cost DESC
LIMIT 1;
The answer to the question is the 10th hour.
hour |
---|
10 |
LIKE & ILIKE in the WHERE Clause
LIKE is a standard SQL operator used in the WHERE clause to find the patterns in values. What does that mean? All the previous operators used in WHERE were looking for the exact values. When you use LIKE, you’re looking for something that is, well, like something. For example, when looking for only a specific word or a particular letter appearing in the whole text.
The ILIKE operator is PostgreSQL-specific. It works the same way as LIKE; only it’s not case-sensitive.
The wildcard characters are also used with those operators since they help look for a part of the value. Most often, it’s '%' wildcard characters used in the following way.
Example | Description |
'%word' | Finds values starting with 'word' |
'word%' | Finds values ending with 'word' |
'%word%' | Finds values containing 'word' in any position |
Question 5
Find drafts which contains the word 'optimism'
“Find drafts which contain the word 'optimism'.”
Link to the question: https://platform.stratascratch.com/coding/9805-find-drafts-which-contains-the-word-optimism
Data
The data is stored in the table google_file_store.
filename | contents |
---|---|
draft1.txt | The stock exchange predicts a bull market which would make many investors happy. |
draft2.txt | The stock exchange predicts a bull market which would make many investors happy, but analysts warn of possibility of too much optimism and that in fact we are awaiting a bear market. |
final.txt | The stock exchange predicts a bull market which would make many investors happy, but analysts warn of possibility of too much optimism and that in fact we are awaiting a bear market. As always predicting the future market is an uncertain game and all investors should follow their instincts and best practices. |
Solution
Select all the columns from the table. The file name has to contain the word 'draft'. We know if the file is a draft, it will begin with the word 'draft'. Therefore, we need to put the wildcard character only at the end.
Also, the contents have to contain the word 'optimism'. It can be in the beginning, at the end, or in the middle of the content. Because of that, the wildcard is needed on both sides of the filtering criteria.
SELECT *
FROM google_file_store
WHERE filename ILIKE 'draft%'
AND contents ILIKE '%optimism%';
The output will be only one draft.
filename | contents |
---|---|
draft2.txt | The stock exchange predicts a bull market which would make many investors happy, but analysts warn of possibility of too much optimism and that in fact we are awaiting a bear market. |
Using WHERE With IN
The IN operator is shorthand for multiple OR operators. The list of criteria is listed in the parentheses, and the where clause looks if the value matches one of those in the list.
Question 6
Find songs that are ranked between 8-10
“Find songs that are ranked between 8-10.
Output the track name along with the corresponding position ordered ascendingly.”
Link to the question: https://platform.stratascratch.com/coding/9999-find-songs-that-are-ranked-between-8-10
Data
The table you’ll work with is spotify_worldwide_daily_song_ranking.
id | position | trackname | artist | streams | url | date | region |
---|---|---|---|---|---|---|---|
303651 | 52 | Heart Won't Forget | Matoma | 28047 | https://open.spotify.com/track/2of2DM5LqTh7ohmmVXUKsH | 2017-02-04 | no |
85559 | 160 | Someone In The Crowd - From "La La Land" Soundtrack | Emma Stone | 17134 | https://open.spotify.com/track/7xE4vKvjqUTtHyJ9zi0k1q | 2017-02-26 | fr |
1046089 | 175 | The Greatest | Sia | 10060 | https://open.spotify.com/track/7xHWNBFm6ObGEQPaUxHuKO | 2017-03-06 | cl |
350824 | 25 | Unforgettable | French Montana | 46603 | https://open.spotify.com/track/3B54sVLJ402zGa6Xm4YGNe | 2017-10-01 | no |
776822 | 1 | Bad and Boujee (feat. Lil Uzi Vert) | Migos | 1823391 | https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR | 2017-01-27 | us |
Solution
First, select the track name and the position. We’re looking for songs in the 8th, 9th, or 10th position. These criteria are written in the parentheses after the IN operator.
SELECT trackname,
position
FROM spotify_worldwide_daily_song_ranking
WHERE POSITION IN (8,
9,
10)
ORDER BY position;
Here are some of the songs that comprise the output.
trackname | position |
---|---|
Attention | 8 |
Alone | 8 |
Make Me (Cry) | 8 |
Perfect Duet (Ed Sheeran & Beyonce) | 8 |
Una Lady Como Tu | 8 |
Aggregate Functions & GROUP BY
The aggregate functions are the types of functions in SQL that perform calculations on a set of rows and return only one value.
The most commonly used aggregate functions are
- COUNT()
- SUM()
- AVG()
- MIN()
- MAX()
The aggregate functions are commonly used with the GROUP BY clause. Using it is necessary whenever there’s any other column in the SELECT statement apart from the aggregate function. In other words, all these columns (except the aggregate function) have to be listed in the GROUP BY clause. Otherwise, it will throw an error.
Note that the columns that appear in the GROUP BY don’t have to appear in the SELECT statement. This means you can group by the columns, but it doesn’t mean you must show these columns in the output.
Question 7
Finding Updated Records
“We have a table with employees and their salaries, however, some of the records are old and contain outdated salary information. Find the current salary of each employee assuming that salaries increase each year. Output their id, first name, last name, department ID, and current salary. Order your list by employee ID in ascending order.”
Link to the question: https://platform.stratascratch.com/coding/10299-finding-updated-records
Data
Here, you’ll work with the table ms_employee_salary.
id | first_name | last_name | salary | department_id |
---|---|---|---|---|
1 | Todd | Wilson | 110000 | 1006 |
1 | Todd | Wilson | 106119 | 1006 |
2 | Justin | Simon | 128922 | 1005 |
2 | Justin | Simon | 130000 | 1005 |
3 | Kelly | Rosario | 42689 | 1002 |
Solution
In the query, select all the columns except the salary. To find the highest salary, use the MAX() function. Data needs to be grouped by all the columns in the SELECT statement, except for the aggregate function.
Finally, data is ordered by the employee’s ID from lowest to highest.
SELECT id,
first_name,
last_name,
department_id,
max(salary) AS max_salary
FROM ms_employee_salary
GROUP BY id,
first_name,
last_name,
department_id
ORDER BY id ASC;
The query will return the following data.
id | first_name | last_name | department_id | salary |
---|---|---|---|---|
1 | Todd | Wilson | 1006 | 110000 |
2 | Justin | Simon | 1005 | 130000 |
3 | Kelly | Rosario | 1002 | 42689 |
4 | Patricia | Powell | 1004 | 170000 |
5 | Sherry | Golden | 1002 | 44101 |
Filtering Data Using HAVING
The HAVING clause has the same purpose as WHERE; it filters data. What you do in the where clause, you can do the same in the HAVING clause.
However, they are not the same. The HAVING clause is used for filtering data after the aggregation, whereas the WHERE clause filters data before the aggregation.This is also reflected in the code: WHERE is written before GROUP BY, while HAVING comes after GROUP BY.
Also, the aggregate functions are allowed in the HAVING clause. In WHERE they are not.
Question 8
3 Bed Minimum
“Find the average number of beds in each neighborhood that has at least 3 beds in total.
Output results along with the neighborhood name and sort the results based on the number of average beds in descending order.”
Link to the question: https://platform.stratascratch.com/coding/9627-3-bed-minimum
Data
This question, too, uses only one table: airbnb_search_details.
id | price | property_type | room_type | amenities | accommodates | bathrooms | bed_type | cancellation_policy | cleaning_fee | city | host_identity_verified | host_response_rate | host_since | neighbourhood | number_of_reviews | review_scores_rating | zipcode | bedrooms | beds |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
12513361 | 555.68 | Apartment | Entire home/apt | {TV,"Wireless Internet","Air conditioning","Smoke detector","Carbon monoxide detector",Essentials,"Lock on bedroom door",Hangers,Iron} | 2 | 1 | Real Bed | flexible | FALSE | NYC | t | 89% | 2015-11-18 | East Harlem | 3 | 87 | 10029 | 0 | 1 |
7196412 | 366.36 | Cabin | Private room | {"Wireless Internet",Kitchen,Washer,Dryer,"Smoke detector","First aid kit","Fire extinguisher",Essentials,"Hair dryer","translation missing: en.hosting_amenity_49","translation missing: en.hosting_amenity_50"} | 2 | 3 | Real Bed | moderate | FALSE | LA | f | 100% | 2016-09-10 | Valley Glen | 14 | 91 | 91606 | 1 | 1 |
16333776 | 482.83 | House | Private room | {TV,"Cable TV",Internet,"Wireless Internet",Kitchen,"Free parking on premises","Pets live on this property",Dog(s),"Indoor fireplace","Buzzer/wireless intercom",Heating,Washer,Dryer,"Smoke detector","Carbon monoxide detector","First aid kit","Safety card","Fire extinguisher",Essentials,Shampoo,"24-hour check-in",Hangers,"Hair dryer",Iron,"Laptop friendly workspace","translation missing: en.hosting_amenity_49","translation missing: en.hosting_amenity_50","Self Check-In",Lockbox} | 2 | 1 | Real Bed | strict | TRUE | SF | t | 100% | 2013-12-26 | Richmond District | 117 | 96 | 94118 | 1 | 1 |
1786412 | 448.86 | Apartment | Private room | {"Wireless Internet","Air conditioning",Kitchen,Heating,"Suitable for events","Smoke detector","Carbon monoxide detector","First aid kit","Fire extinguisher",Essentials,Shampoo,"Lock on bedroom door",Hangers,"translation missing: en.hosting_amenity_49","translation missing: en.hosting_amenity_50"} | 2 | 1 | Real Bed | strict | TRUE | NYC | t | 93% | 2010-05-11 | Williamsburg | 8 | 86 | 11211 | 1 | 1 |
14575777 | 506.89 | Villa | Private room | {TV,Internet,"Wireless Internet","Air conditioning",Kitchen,"Free parking on premises",Essentials,Shampoo,"translation missing: en.hosting_amenity_49","translation missing: en.hosting_amenity_50"} | 6 | 2 | Real Bed | strict | TRUE | LA | t | 70% | 2015-10-22 | 2 | 100 | 90703 | 3 | 3 |
Solution
In the solution, you should select the column neighborhood and then use the AVG() function to calculate the average number of beds by neighborhood.
The output has to show only the neighborhood with at least 3 beds, so this criteria has to appear in the HAVING clause. To get the number of beds, use the SUM() function.
Finally, order data from the highest to the lowest average number of beds.
SELECT neighbourhood,
AVG(beds) AS n_beds_avg
FROM airbnb_search_details
GROUP BY neighbourhood
HAVING SUM(beds) >= 3
ORDER BY n_beds_avg DESC;
Here’s the solution output.
neighbourhood | n_beds_avg |
---|---|
Pacific Palisades | 6 |
Redondo Beach | 5 |
Windsor Terrace | 5 |
Hayes Valley | 5 |
Hell's Kitchen | 4 |