Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hacker rank #5

Open
goku-1995 opened this issue Apr 30, 2024 · 0 comments
Open

Hacker rank #5

goku-1995 opened this issue Apr 30, 2024 · 0 comments

Comments

@goku-1995
Copy link

Revising the select Query I

  1. Query all columns for all American cities in the CITY table with populations larger than 100000. The CountryCode for America is USA.
    The CITY table is described as follows:

select *
from city
where CountryCode = 'USA' and population > 100000;

Revising the Select Query II

  1. Query the NAME field for all American cities in the CITY table with populations larger than 120000. The CountryCode for America is USA.
    The CITY table is described as follows:

select name
from city
where countrycode='USA' and population>120000

Select All

  1. Query all columns (attributes) for every row in the CITY table.
    The CITY table is described as follows:

select * from city

Select By ID

  1. Query all columns for a city in CITY with the ID 1661.
    The CITY table is described as follows:

Select * from city where id=1661

Japanese Cities' Attributes

  1. Query all attributes of every Japanese city in the CITY table. The COUNTRYCODE for Japan is JPN. The CITY table is described as follows:

Select *
from city
where COUNTRYCODE="JPN"

Japanese Cities' Names

  1. Query the names of all the Japanese cities in the CITY table. The COUNTRYCODE for Japan is JPN.
    The CITY table is described as follows:

Select name
from CITY
where COUNTRYCODE = 'JPN'

Weather Observation Station 1

  1. Query a list of CITY and STATE from the STATION table.
    The STATION table is described as follows:

select city,state
from station

Weather Observation Station 3

  1. Query a list of CITY names from STATION for cities that have an even ID number. Print the results in any order, but exclude duplicates from the answer.
    The STATION table is described as follows:

select distinct city
from station
where ID%2=0

Weather Observation Station 4

9.Find the difference between the total number of CITY entries in the table and the number of distinct CITY entries in the table.
The STATION table is described as follows:

SELECT COUNT(city) - COUNT(DISTINCT city)
FROM station;

Weather Observation Station 5

  1. Query the two cities in STATION with the shortest and longest CITY names, as well as their respective lengths (i.e.: number of characters in the name). If there is more than one smallest or largest city, choose the one that comes first when ordered alphabetically.
    The STATION table is described as follows:

(select city, length(city)
from station
order by LENGTH(CITY) asc, city limit 1)
union all
(select city, length(city)
from station
order by LENGTH(CITY) desc, city limit 1)

Weather Observation Station 6

  1. Query the list of CITY names starting with vowels (i.e., a, e, i, o, or u) from STATION. Your result cannot contain duplicates.
    Input Format

select distinct city
from station
where city REGEXP '^[aeiou]'

Weather Observation Station 7

  1. Query the list of CITY names ending with vowels (a, e, i, o, u) from STATION. Your result cannot contain duplicates.

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';

Weather Observation Station 8

  1. Query the list of CITY names from STATION which have vowels (i.e., a, e, i, o, and u) as both their first and last characters. Your result cannot contain duplicates.

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')

Weather Observation Station 9

  1. Query the list of CITY names from STATION that do not start with vowels. Your result cannot contain duplicates.

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%';

Weather Observation Station 10

  1. Query the list of CITY names from STATION that do not end with vowels. Your result cannot contain duplicates.

select distinct city
from station
where upper(substr(city, length(city), 1)) not in ('A','E','I','O','U')
and lower(substr(city, length(city),1)) not in ('a','e','i','o','u');

Weather Observation Station 11

  1. Query the list of CITY names from STATION that either do not start with vowels or do not end with vowels. Your result cannot contain duplicates.

select distinct city
from station
where lower(substr(city,1,1)) not in ('a','e','i','o','u')
or lower(substr(city, length(city),1)) not in ('a','e','i','o','u')

Weather Observation Station 12

  1. Query the list of CITY names from STATION that do not start with vowels and do not end with vowels. Your result cannot contain duplicates.

select distinct city
from station
where lower(substr(city,1,1)) not in ('a','e','i','o','u')
and lower(substr(city,length(city),1)) not in ('a','e','i','o','u')

Higher Than 75 Marks

  1. Query the Name of any student in STUDENTS who scored higher than 75 Marks. Order your output by the last three characters of each name. If two or more students both have names ending in the same last three characters (i.e.: Bobby, Robby, etc.), secondary sort them by ascending ID.

select name
from students
where marks > 75
order by right (name,3), id

Employee Names

  1. Write a query that prints a list of employee names (i.e.: the name attribute) from the Employee table in alphabetical order.

select name
from employee
order by name

Employee Salaries

  1. Write a query that prints a list of employee names (i.e.: the name attribute) for employees in Employee having a salary greater than $2000 per month who have been employees for less than 10 months. Sort your result by ascending employee_id.

select name
from employee
where salary>2000 and months<10 order by employee_id

Type of Triangle

  1. Write a query identifying the type of each record in the TRIANGLES table using its three side lengths. Output one of the following statements for each record in the table:

Equilateral: It's a triangle with sides of equal length.
Isosceles: It's a triangle with sides of equal length.
Scalene: It's a triangle with sides of differing lengths.
Not A Triangle: The given values of A, B, and C don't form a 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 b=c or a=c then 'Isosceles'
else 'Scalene'
end as tri
from triangles;

Revising Aggregations - The Count Function

  1. Query a count of the number of cities in CITY having a Population larger than 100,000.

SELECT COUNT(POPULATION)
FROM CITY
WHERE POPULATION > 100000;

Revising Aggregations - The Sum Function

  1. Query the total population of all cities in CITY where District is California.

select sum(population)
from city
where district = 'California'

Revising Aggregations - Averages

  1. Query the average population of all cities in CITY where District is California.

select avg (population)
from city
where district ='california'

Average Population

  1. Query the average population for all cities in CITY, rounded down to the nearest integer.

select round(avg(population))
from city

Japan Population

  1. Query the sum of the populations for all Japanese cities in CITY. The COUNTRYCODE for Japan is JPN.

select sum(population)
from city
where COUNTRYCODE ='JPN'

Population Density Difference

  1. Query the difference between the maximum and minimum populations in CITY.

select max(population) - min(population)
from city

The Blunder

  1. Samantha was tasked with calculating the average monthly salaries for all employees in the EMPLOYEES table, but did not realize her keyboard's 0 key was broken until after completing the calculation. She wants your help finding the difference between her miscalculation (using salaries with any zeros removed), and the actual average salary.
    Write a query calculating the amount of error (i.e.: average monthly salaries), and round it up to the next integer.

select ceil(avg(salary) - avg(replace(salary,0,'')))
from employees

Top Earners

  1. We define an employee's total earnings to be their monthly salary * months worked, and the maximum total earnings to be the maximum total earnings for any employee in the Employee table. Write a query to find the maximum total earnings for all employees as well as the total number of employees who have maximum total earnings. Then print these values as 2 space-separated integers.

SELECT (monthssalary) as earnings, COUNT()
FROM Employee
GROUP BY earnings
ORDER BY earnings DESC
LIMIT 1;

Weather Observation Station 13

  1. Query the sum of Northern Latitudes (LAT_N) from STATION having values greater than 38.7880 and less than 137.2345. Truncate your answer to 4 decimal places.

SELECT ROUND(SUM(LAT_N),4)
FROM STATION
WHERE LAT_N > 38.7880 AND LAT_N < 137.2345;

Weather Observation Station 14

  1. Query the greatest value of the Northern Latitudes (LAT_N) from STATION that is less than 137.2345. Truncate your answer to 4 decimal places.

SELECT ROUND(max(LAT_N),4)
FROM STATION
where LAT_N < 137.2345

Weather Observation Station 16

  1. Query the smallest Northern Latitude (LAT_N) from STATION that is greater than 38.7780. Round your answer to 4 decimal places.

select round(min(lat_n),4)
from station
where LAT_N > 38.7780

Population Census

  1. Given the CITY and COUNTRY tables, query the sum of the populations of all cities where the CONTINENT is 'Asia'.

Note: CITY.CountryCode and COUNTRY.Code are matching key columns.

select sum(city.population)
from city
join Country
on CITY.CountryCode = COUNTRY.Code
where country.continent ='Asia'

African Cities

  1. Given the CITY and COUNTRY tables, query the names of all cities where the CONTINENT is 'Africa'.
    Note: CITY.CountryCode and COUNTRY.Code are matching key columns.

select city.name
from city
join country
on CITY.CountryCode = COUNTRY.Code
where country.continent ='africa';

Average Population of Each Continent

  1. Given the CITY and COUNTRY tables, query the names of all the continents (COUNTRY.Continent) and their respective average city populations (CITY.Population) rounded down to the nearest integer.
    Note: CITY.CountryCode and COUNTRY.Code are matching key columns.

SELECT COUNTRY.Continent, floor(AVG(CITY.Population))
FROM CITY
JOIN COUNTRY ON CITY.CountryCode = COUNTRY.Code
GROUP BY COUNTRY.Continent

The Report

  1. You are given two tables: Students and Grades. Students contains three columns ID, Name and Marks.
    Ketty gives Eve a task to generate a report containing three columns: Name, Grade and Mark. Ketty doesn't want the NAMES of those students who received a grade lower than 8. The report must be in descending order by grade -- i.e. higher grades are entered first. If there is more than one student with the same grade (8-10) assigned to them, order those particular students by their name alphabetically. Finally, if the grade is lower than 8, use "NULL" as their name and list them by their grades in descending order. If there is more than one student with the same grade (1-7) assigned to them, order those particular students by their marks in ascending order.Write a query to help Eve.

select if(grade<8,null,name), grade, marks
from students as s join grades as g
where s.marks between g.min_mark and g.max_mark
order by grade desc,name asc

SQL Project Planning

  1. You are given a table, Projects, containing three columns: Task_ID, Start_Date and End_Date. It is guaranteed that the difference between the End_Date and the Start_Date is equal to 1 day for each row in the table.
    If the End_Date of the tasks are consecutive, then they are part of the same project. Samantha is interested in finding the total number of different projects completed.
    Write a query to output the start and end dates of projects listed by the number of days it took to complete the project in ascending order. If there is more than one project that have the same number of completion days, then order by the start date of the project.

SELECT Start_Date, min(End_Date)
FROM
(SELECT Start_Date FROM Projects WHERE Start_Date NOT IN (SELECT End_Date FROM Projects)) a ,
(SELECT End_Date FROM Projects WHERE End_Date NOT IN (SELECT Start_Date FROM Projects)) b
WHERE Start_Date < End_Date
GROUP BY Start_Date
ORDER BY DATEDIFF(min(End_Date), Start_Date) ASC, Start_Date ASC;

Placements

  1. You are given three tables: Students, Friends and Packages. Students contains two columns: ID and Name. Friends contains two columns: ID and Friend_ID (ID of the ONLY best friend). Packages contains two columns: ID and Salary (offered salary in $ thousands per month).

select s.Name
from students as s
join friends as f on s.id=f.id
join packages as p on f.Friend_ID=p.id
join packages as p1 on s.id=p1.id
where p.salary>p1.salary
order by p.salary

Weather Observation Station 2

  1. Query the following two values from the STATION table:
    The sum of all values in LAT_N rounded to a scale of decimal places.
    The sum of all values in LONG_W rounded to a scale of decimal places.

select round(sum(LAT_N),2), round(sum(LONG_W),2)
from station

Weather Observation Station 15

  1. Query the Western Longitude (LONG_W) for the largest Northern Latitude (LAT_N) in STATION that is less than 137.2345 . Round your answer to 4 decimal places.

select round(LONG_W,4)
from station
where LAT_N < 137.2345
order by LAT_N desc limit 1

Weather Observation Station 17

  1. Query the Western Longitude (LONG_W)where the smallest Northern Latitude (LAT_N) in STATION is greater than 38.7780. Round your answer to 4 decimal places.

select round(LONG_W,4)
from Station
where LAT_N > 38.7780
order by LAT_N asc limit 1

Draw The Triangle 1

  1. P(R) represents a pattern drawn by Julia in R rows. The following pattern represents P(5):



Write a query to print the pattern P(20).

SELECT REPEAT('* ', 20 - number) AS pattern
FROM (
SELECT 0 AS number UNION
SELECT 1 UNION
SELECT 2 UNION
SELECT 3 UNION
SELECT 4 UNION
SELECT 5 UNION
SELECT 6 UNION
SELECT 7 UNION
SELECT 8 UNION
SELECT 9 UNION
SELECT 10 UNION
SELECT 11 UNION
SELECT 12 UNION
SELECT 13 UNION
SELECT 14 UNION
SELECT 15 UNION
SELECT 16 UNION
SELECT 17 UNION
SELECT 18 UNION
SELECT 19 UNION
SELECT 20
) AS numbers;

Draw The Triangle 2

  1. P(R) represents a pattern drawn by Julia in R rows. The following pattern represents P(5):



Write a query to print the pattern P(20).

SELECT REPEAT('* ', 20 - number) AS pattern
FROM (
SELECT 0 AS number UNION
SELECT 1 UNION
SELECT 2 UNION
SELECT 3 UNION
SELECT 4 UNION
SELECT 5 UNION
SELECT 6 UNION
SELECT 7 UNION
SELECT 8 UNION
SELECT 9 UNION
SELECT 10 UNION
SELECT 11 UNION
SELECT 12 UNION
SELECT 13 UNION
SELECT 14 UNION
SELECT 15 UNION
SELECT 16 UNION
SELECT 17 UNION
SELECT 18 UNION
SELECT 19 UNION
SELECT 20
) AS numbers;

Weather Observation Station 18

  1. Consider p1 (a,b) and p2 (c,d) to be two points on a 2D plane.

a happens to equal the minimum value in Northern Latitude (LAT_N in STATION).
b happens to equal the minimum value in Western Longitude (LONG_W in STATION).
c happens to equal the maximum value in Northern Latitude (LAT_N in STATION).
d happens to equal the maximum value in Western Longitude (LONG_W in STATION).
Query the Manhattan Distance between points p1 and p2 and round it to a scale of decimal 4 places.

select round(ABS(min(LAT_N)-max(LAT_N))+ABS(min(LONG_W)-max(LONG_W)),4)
from station

Weather Observation Station 19

  1. Consider p1 (a,b) and p2 (c,d)to be two points on a 2D plane where (a,b) are the respective minimum and maximum values of Northern Latitude (LAT_N) and (c,d) are the respective minimum and maximum values of Western Longitude (LONG_W) in STATION.

Query the Euclidean Distance between points p1 and p2 and format your answer to display 4 decimal digits.

select round(sqrt((max(LAT_N) - min(LAT_N)) * (max(LAT_N) - (min(LAT_N)))+((max(LONG_W) - min(LONG_W))*(max(LONG_W) - min(LONG_W)))),4)
from station

Top Competitors

  1. Julia just finished conducting a coding contest, and she needs your help assembling the leaderboard! Write a query to print the respective hacker_id and name of hackers who achieved full scores for more than one challenge. Order your output in descending order by the total number of challenges in which the hacker earned a full score. If more than one hacker received full scores in same number of challenges, then sort them by ascending hacker_id.

Select s.hacker_id, h.name
from submissions as s
inner join hackers as h
on s.hacker_id = h.hacker_id
inner join challenges as c
on s.challenge_id = c.challenge_id
inner join difficulty as d
on c.difficulty_level = d.difficulty_level
where s.score = d.score
group by s.hacker_id, h.name
having count() > 1
order by count(
) desc, s.hacker_id

Weather Observation Station 20

  1. A median is defined as a number separating the higher half of a data set from the lower half. Query the median of the Northern Latitudes (LAT_N) from STATION and round your answer to decimal places.

-- select count(LAT_N)
-- from station

select round(LAT_N,4)
from station
order by LAT_N
limit 1 offset 249

Contest Leaderboard

  1. You did such a great job helping Julia with her last coding contest challenge that she wants you to work on this one, too!
    The total score of a hacker is the sum of their maximum scores for all of the challenges. Write a query to print the hacker_id, name, and total score of the hackers ordered by the descending score. If more than one hacker achieved the same total score, then sort the result by ascending hacker_id. Exclude all hackers with a total score of from your result.

-- select hacker_id, name, total score
-- order by desc, total score >0

select m.hacker_id, h.name, sum(score) as total_score from
(select hacker_id, challenge_id, max(score) as score
from Submissions group by hacker_id, challenge_id) as m
join Hackers as h
on m.hacker_id = h.hacker_id
group by m.hacker_id, h.name
having total_score > 0
order by total_score desc, m.hacker_id;

New Companies

  1. Amber's conglomerate corporation just acquired some new companies. Each of the companies follows this hierarchy:
    Given the table schemas below, write a query to print the company_code, founder name, total number of lead managers, total number of senior managers, total number of managers, and total number of employees. Order your output by ascending
    company_code.

SELECT c.company_code, c.founder,
COUNT(DISTINCT(e.lead_manager_code)),
COUNT(DISTINCT(e.senior_manager_code)),
COUNT(DISTINCT(e.manager_code)),
COUNT(DISTINCT(e.employee_code))
FROM company AS c
JOIN employee AS e
ON c.company_code = e.company_code
GROUP BY c.company_code, c.founder
ORDER BY c.company_code

Symmetric Pairs

  1. You are given a table, Functions, containing two columns: X and Y.
    Two pairs (X1, Y1) and (X2, Y2) are said to be symmetric pairs if X1 = Y2 and X2 = Y1.Write a query to output all such symmetric pairs in ascending order by the value of X. List the rows such that X1 ≤ Y1.

SELECT x, y
FROM functions
WHERE (x, y) IN (SELECT y, x FROM functions) GROUP BY x, y HAVING x < y OR (x = y AND COUNT(*) > 1)
ORDER BY x;

You are given a table, BST, containing two columns: N and P, where N represents the value of a node in Binary Tree, and P is the parent of N.

Binary Tree Nodes

  1. Write a query to find the node type of Binary Tree ordered by the value of the node. Output one of the following for each node:
    Root: If node is root node.
    Leaf: If node is leaf node.
    Inner: If node is neither root nor leaf node.

select n, case
when p is null then 'Root'
when n in (select p from BST) then 'Inner'
else 'Leaf'
end from BST
order by n;

Ollivander's Inventory

  1. Harry Potter and his friends are at Ollivander's with Ron, finally replacing Charlie's old broken wand.
    Hermione decides the best way to choose is by determining the minimum number of gold galleons needed to buy each non-evil wand of high power and age. Write a query to print the id, age, coins_needed, and power of the wands that Ron's interested in, sorted in order of descending power. If more than one wand has same power, sort the result in order of descending age.

select w.id,wp.age,w.coins_needed,w.power
from Wands w
inner join Wands_property wp
on w.code=wp.code and wp.is_evil=0
where w.coins_needed=(select min(coins_needed)
from Wands where code=w.code and power=w.power)
order by power desc,age desc;

Occupations

  1. Pivot the Occupation column in OCCUPATIONS so that each Name is sorted alphabetically and displayed underneath its corresponding Occupation. The output column headers should be Doctor, Professor, Singer, and Actor, respectively.

SELECT Doctor, Professor, Singer, Actor
FROM(SELECT ROW_NUMBER() OVER (PARTITION BY OCCUPATION ORDER BY NAME) as RowNumber, * FROM OCCUPATIONS) as Temp_Table
PIVOT
(MIN(Name) FOR Occupation IN (Doctor,Professor,Singer,Actor))
as Pivot_Table;

The PADS

  1. Generate the following two result sets:
    Query an alphabetically ordered list of all names in OCCUPATIONS, immediately followed by the first letter of each profession as a parenthetical (i.e.: enclosed in parentheses). For example: AnActorName(A), ADoctorName(D), AProfessorName(P), and ASingerName(S).
    Query the number of ocurrences of each occupation in OCCUPATIONS. Sort the occurrences in ascending order, and output them in the following format:
    There are a total of [occupation_count] [occupation]s.
    where [occupation_count] is the number of occurrences of an occupation in OCCUPATIONS and [occupation] is the lowercase occupation name. If more than one Occupation has the same [occupation_count], they should be ordered alphabetically.

SELECT CONCAT(NAME,'(',SUBSTR(OCCUPATION,1,1),')')
FROM OCCUPATIONS
ORDER BY NAME;
SELECT CONCAT('There are a total of ',COUNT(OCCUPATION),' ',lower(OCCUPATION),'s.')
FROM OCCUPATIONS
GROUP BY OCCUPATION
ORDER BY COUNT(OCCUPATION) ASC, OCCUPATION asc;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant