0% found this document useful (0 votes)
20 views

SQL Solutions

Uploaded by

animeshsingh2207
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

SQL Solutions

Uploaded by

animeshsingh2207
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

SQL HACKERANK SOLUTION

Solution 1 : ( REVISING THE SELECT QUERY 1 )


SELECT *
FROM CITY
WHERE CountryCode = 'USA'
AND Population > 100000;
Solution 2 : ( REVISING THE SELECT QUERY 2 )
SELECT NAME
FROM CITY
WHERE CountryCode = 'USA'
AND Population > 120000;
------
SELECT FLOOR(AVG(Population))
FROM CITY;
Solution 3 : ( SELECT ALL )
SELECT *
FROM CITY;
---
SELECT SUM(Population)
FROM CITY
WHERE CountryCode = 'JPN';
Solution 4 : ( SELECT BY ID )
SELECT *
FROM CITY
WHERE ID = 1661;
SELECT MAX(Population) - MIN(Population) AS PopulationDifference
FROM CITY;
Solution 5 : ( JAPANSESE CITIES ATTRIBUTES )
SELECT *
FROM CITY
WHERE CountryCode = 'JPN';

SOLUTION 6 : ( JAPANESE CITIES NAMES )


SELECT NAME
FROM CITY
WHERE CountryCode = 'JPN';

SOLUTION 7 : ( WEATHER OBSERVATION STATION 1 )


SELECT CITY, STATE
FROM STATION;

SOLUTION 8 : ( WEATHER OBSERVATION STATION 3 )


SELECT DISTINCT CITY
FROM STATION
WHERE ID / 2 * 2 = ID;

SOLUTION 9 : ( WEATHER OBSERVATION STATION 4 )


SELECT COUNT(CITY) - COUNT(DISTINCT CITY) AS CityDifference
FROM STATION;

SOLUTION 10 : ( WEATHER OBSERVATION STATION 5 )


SELECT CITY, LENGTH(CITY) AS NameLength
FROM STATION
ORDER BY LENGTH(CITY), CITY
LIMIT 1;

SELECT CITY, LENGTH(CITY) AS NameLength


FROM STATION
ORDER BY LENGTH(CITY) DESC, CITY
LIMIT 1;

SOLUTION 11 ( WEATHER OBSERVATION STATION 6 )

SELECT DISTINCT CITY

FROM STATION

WHERE CITY LIKE 'A%' OR

CITY LIKE 'E%' OR

CITY LIKE 'I%' OR

CITY LIKE 'O%' OR

CITY LIKE 'U%';

SOLUTION 12 ( WEATHER OBSERVATION STATION 7 )

SELECT DISTINCT CITY

FROM STATION

WHERE LOWER(CITY) LIKE '%a' OR

LOWER(CITY) LIKE '%e' OR

LOWER(CITY) LIKE '%i' OR

LOWER(CITY) LIKE '%o' OR

LOWER(CITY) LIKE '%u';


SOLUTION 13 ( WEATHER OBSERVATION STATION 8 )

SELECT DISTINCT CITY

FROM STATION

WHERE (CITY LIKE 'A%' OR CITY LIKE 'E%' OR CITY LIKE 'I%' OR CITY LIKE 'O%' OR CITY LIKE 'U%')

AND (CITY LIKE '%a' OR CITY LIKE '%e' OR CITY LIKE '%i' OR CITY LIKE '%o' OR CITY LIKE '%u');

SOLUTION 14 ( WEATHER OBSERVATION STATION 9 )

SELECT DISTINCT CITY

FROM STATION

WHERE CITY NOT LIKE 'A%' AND

CITY NOT LIKE 'E%' AND

CITY NOT LIKE 'I%' AND

CITY NOT LIKE 'O%' AND

CITY NOT LIKE 'U%';

SOLUTION 15 ( WEATHER OBSERVATION STATION 10 )

SELECT DISTINCT CITY

FROM STATION

WHERE CITY NOT LIKE '%a' AND

CITY NOT LIKE '%e' AND

CITY NOT LIKE '%i' AND

CITY NOT LIKE '%o' AND

CITY NOT LIKE '%u';

SOLUTION 16 ( WEATHER OBSERVATION STATION 11 )

SELECT DISTINCT CITY

FROM STATION
WHERE CITY NOT LIKE 'A%' AND

CITY NOT LIKE 'E%' AND

CITY NOT LIKE 'I%' AND

CITY NOT LIKE 'O%' AND

CITY NOT LIKE 'U%'

OR CITY NOT LIKE '%a' AND

CITY NOT LIKE '%e' AND

CITY NOT LIKE '%i' AND

CITY NOT LIKE '%o' AND

CITY NOT LIKE '%u';

SOLUTION 17 ( WEATHER OBSERVATION STATION 12 )

SELECT DISTINCT CITY

FROM STATION

WHERE CITY NOT LIKE 'A%' AND

CITY NOT LIKE 'E%' AND

CITY NOT LIKE 'I%' AND

CITY NOT LIKE 'O%' AND

CITY NOT LIKE 'U%'

AND CITY NOT LIKE '%a' AND

CITY NOT LIKE '%e' AND

CITY NOT LIKE '%i' AND

CITY NOT LIKE '%o' AND

CITY NOT LIKE '%u';

SOLUTION 18 ( HIGHER THAN 75 )

SELECT Name
FROM STUDENTS

WHERE Marks > 75

ORDER BY RIGHT(Name, 3), ID;

SOLUTION 19 ( EMPLOYEE NAMES )

SELECT name

FROM Employee

ORDER BY name;

SOLUTION 20 ( EMPOYEES SALARIES )

SELECT name

FROM Employee

WHERE salary > 2000 AND months < 10

ORDER BY employee_id;

SOLUTION 21 ( TYPE OF TRIANGLE )

SELECT

CASE

WHEN A + B <= C OR A + C <= B OR B + C <= A THEN 'Not A Triangle'

WHEN A = B AND B = C THEN 'Equilateral'

WHEN A = B OR A = C OR B = C THEN 'Isosceles'

ELSE 'Scalene'

END AS TriangleType

FROM TRIANGLES;

SOLUTION 22 ( THE PADS )

SELECT NAME || '(' || LEFT(Occupation, 1) || ')'


FROM OCCUPATIONS

ORDER BY NAME;

SELECT 'There are a total of ' || COUNT(Occupation) || ' ' || LOWER(Occupation) || 's.'

FROM OCCUPATIONS

GROUP BY Occupation

ORDER BY COUNT(Occupation), Occupation;

Explanation:

First Query: Outputs the name followed by the first letter of the occupation in parentheses.

Second Query: Counts the number of each occupation, converts the occupation to lowercase, and
formats the output string as required (There are a total of [count] [occupation]s.).

Both queries should work correctly now without any function-related errors.

SOLUTION 23 ( BINARY TREE NODES )

WITH Parents AS (

SELECT DISTINCT P AS parent FROM BST WHERE P IS NOT NULL

),

Children AS (

SELECT DISTINCT N AS child FROM BST

SELECT

N,

CASE

WHEN P IS NULL THEN 'Root'

WHEN N NOT IN (SELECT parent FROM Parents) THEN 'Leaf'

ELSE 'Inner'

END AS node_type

FROM BST
ORDER BY N;

Explanation :

Common Table Expressions (CTEs):

Parents: This CTE extracts all distinct parent values from the P column. It identifies which nodes are
parents.

Children: This CTE extracts all distinct node values from the N column.

Main Query:

For each node in the BST, it checks:

If the parent P is NULL, the node is classified as 'Root'.

If the node N is not in the list of parents, it is classified as 'Leaf'.

If neither of the above conditions is true, it is classified as 'Inner'.

Output Order:

Finally, the result is ordered by the value of the node (N).

SOLUTION 24 ( AVERAGE POPULATION )

SELECT FLOOR(AVG(Population))
FROM CITY;

SOLUTION 25 ( JAPAN POPULATION )


SELECT SUM(POPULATION) AS Population_Density
FROM CITY
WHERE COUNTRYCODE = 'JPN';

SOLUTION 26 ( NEW COMPANIES )


SELECT
c.company_code,
c.founder,
COUNT(DISTINCT lm.lead_manager_code) AS total_lead_managers,
COUNT(DISTINCT sm.senior_manager_code) AS total_senior_managers,
COUNT(DISTINCT m.manager_code) AS total_managers,
COUNT(DISTINCT e.employee_code) AS total_employees
FROM
Company c
LEFT JOIN
Lead_Manager lm ON c.company_code = lm.company_code
LEFT JOIN
Senior_Manager sm ON lm.lead_manager_code = sm.lead_manager_code
LEFT JOIN
Manager m ON sm.senior_manager_code = m.senior_manager_code
LEFT JOIN
Employee e ON m.manager_code = e.manager_code
GROUP BY
c.company_code, c.founder
ORDER BY
c.company_code;
Explanation:
Company c: The base table with company_code and founder.
LEFT JOIN: We join each table based on the corresponding key. We use LEFT JOIN to ensure that
all companies are included in the result, even if they don't have lead managers, senior
managers, etc.
COUNT(DISTINCT ...): Used to avoid counting duplicates, especially if there are duplicate records
in the tables.
GROUP BY: We group by company_code and founder to aggregate the counts for each
company.
ORDER BY c.company_code: Ensures the results are sorted alphabetically by company_code.
This query will give you the desired output of company_code, founder, total lead managers,
total senior managers, total managers, and total employees, all ordered by company_code as
required.
SOLUTION 27 ( AVERAGE POPULATION OF EACH CONTINENT )
SELECT
co.Continent,
FLOOR(AVG(ci.Population)) AS AvgCityPopulation
FROM
CITY ci
JOIN
COUNTRY co
ON
ci.CountryCode = co.Code
GROUP BY
co.Continent;

SOLUTION 28 ( THE REPORT )


SELECT
CASE
WHEN g.Grade < 8 THEN 'NULL'
ELSE s.Name
END AS Name,
g.Grade,
s.Marks
FROM
Students s
JOIN
Grades g
ON
s.Marks BETWEEN g.Min_Mark AND g.Max_Mark
ORDER BY
g.Grade DESC,
CASE
WHEN g.Grade >= 8 THEN s.Name
ELSE s.Marks
END ASC;
Explanation :
CASE Statement:
CASE checks if the grade is less than 8. If it is, we display 'NULL' as the name.
Otherwise, we display the actual student's name.
JOIN:
The Students table is joined with the Grades table using the condition that the student's marks
fall within the range of marks corresponding to the grade (Marks BETWEEN g.Min_Mark AND
g.Max_Mark).
ORDER BY:
First, sort by g.Grade in descending order.
For grades 8 or higher, students are ordered by their Name alphabetically.
For grades lower than 8, the Marks are used to order the students in ascending order.

SOLUTION 29 ( TOP COMPETITORS )


SELECT
h.hacker_id,
h.name
FROM
Hackers h
JOIN
Submissions s
ON
h.hacker_id = s.hacker_id
JOIN
Challenges c
ON
s.challenge_id = c.challenge_id
JOIN
Difficulty d
ON
c.difficulty_level = d.difficulty_level
WHERE
s.score = d.score
GROUP BY
h.hacker_id, h.name
HAVING
COUNT(s.challenge_id) > 1
ORDER BY
COUNT(s.challenge_id) DESC,
h.hacker_id ASC;
Explanation :
JOIN the necessary tables:
We join the Hackers table (h) with the Submissions table (s) to get the submissions made by
each hacker.
Then, we join with the Challenges table (c) to get the challenge_id and its associated
difficulty_level.
Finally, we join with the Difficulty table (d) to compare the score in the Submissions table with
the maximum score for each difficulty_level.
WHERE clause:
The condition s.score = d.score ensures that we only consider submissions where the hacker
achieved the full score for the challenge.
GROUP BY:
We group by the hacker's hacker_id and name to aggregate the challenges in which they earned
a full score.
HAVING clause:
The HAVING COUNT(s.challenge_id) > 1 filters out hackers who have achieved a full score in only
one challenge. We only want hackers with more than one full score.
ORDER BY:
The result is ordered by the number of challenges in which the hacker achieved a full score
(COUNT(s.challenge_id)) in descending order.
If multiple hackers have the same count, we order them by hacker_id in ascending order.

You might also like