--Salaries Differences
 --Write a query that calculates the difference between the highest 
 --salaries found in the marketing and engineering departments.
 --Output just the absolute difference in salaries.
    --Напишите запрос, который вычисляет разницу между самыми высокими зарплатами, 
    -- найденными в отделах маркетинга и инженерии. Выведите только абсолютную разницу в зарплатах.

SELECT ABS((MAX(salary) FILTER (WHERE department = 'engineering')) - MAX(salary) FILTER (WHERE department = 'marketing'))
FROM db_employee LEFT JOIN
db_dept ON db_employee.department_id = db_dept.id

--db_employee
--id:int
--first_name:varchar
--last_name:varchar
--salary:int
--department_id:int

--db_dept
--id:int
--department:varchar

                --Reviews of Hotel Arena
--Find the number of rows for each review score earned by 'Hotel Arena'. Output the hotel name 
    --(which should be 'Hotel Arena'), 
--review score along with the corresponding number of rows with that score for the specified hotel.

select  hotel_name,
reviewer_score,
count(*)
from hotel_reviews
where hotel_name = 'Hotel Arena'
group by 1, 2

              --Popularity of Hack
    --Meta/Facebook разработали новый язык программирования под названием Hack.To измерения 
    --популярности Hack они провели опрос среди своих сотрудников. Опрос включал данные о предыдущем 
   -- знакомстве с программированием, а также о количестве лет опыта, возрасте, поле и, самое главное, 
   -- удовлетворенности Hack. Из-за ошибки данные о местоположении не были собраны, но ваш руководитель 
    --требует отчет, показывающий среднюю популярность Hack по расположению офиса. К счастью, идентификаторы 
    --пользователей, заполняющих опросы, были сохранены.
--Исходя из вышесказанного, найдите среднюю популярность Hack по офисному местоположению.
--Выведите местоположение вместе со средней популярностью.

    
select location, 
AVG(popularity) avg_popularity
from facebook_employees
LEFT JOIN facebook_hack_survey
ON facebook_employees.id = facebook_hack_survey.employee_id
GROUP BY 1


             --Find how many times each artist appeared on the Spotify ranking list

--Узнайте, сколько раз каждый исполнитель появлялся в рейтинге Spotify
--Выведите имя исполнителя вместе с соответствующим количеством вхождений.
--Упорядочивайте записи по количеству вхождений в порядке убывания.

select artist,
COUNT(artist) n_occurences
from spotify_worldwide_daily_song_ranking
group by 1
order by 2 desc


                     --Find the base pay for Police Captains

--Find the base pay for Police Captains.
--Output the employee name along with the corresponding base pay.

select employeename,
basepay 
from sf_public_salaries
where jobtitle like '%CAPTAIN%POLICE%'


               --Average Salaries
--Сравните зарплату каждого сотрудника со средней зарплатой соответствующего отдела.
--Выведите название отдела, имя и зарплату сотрудника, а также среднюю заработную плату этого отдела.

select department,	
first_name,	
salary,	
AVG(salary) over(partition by department) avg
from employee


                  --Order Details
--Ознакомьтесь с подробной информацией о заказе, сделанном Джилл и Евой.
--Считайте Джилл и Еву именами клиентов.
--Выведите дату заказа, детали и стоимость вместе с именем.
--Записи заказов на основе идентификатора клиента в порядке возрастания.

select first_name,
order_date,
order_details,
total_order_cost
from customers left join orders on customers.id = orders.cust_id
where first_name in ('Jill', 'Eva')


             --Number of Workers by Department Starting in April or Later
--Найдите количество работников по отделам, которые присоединились к команде или после апреля.
--Выведите название отдела вместе с соответствующим количеством работников.
--Сортировка записей по количеству исполнителей в порядке убывания.

select department,
count(worker_id) num_workers
from worker
where date_part('month', joining_date) >= 4
group by 1
order by 2 desc


                     --Number of Shipments Per Month
--Напишите запрос, который будет подсчитывать количество отгрузок в месяц. 
--Уникальный ключ для одного отправления представляет собой комбинацию shipment_id и sub_id. 
--Выведите year_month в формате ГГГГ-ММ и количество отгрузок в этом месяце.

select  to_char(shipment_date, 'YYYY-MM') year_month,
count(distinct(shipment_id, sub_id))
from amazon_shipment
group by 1


            --Unique Users Per Client Per Month

--Write a query that returns the number of unique users per client per month

select client_id,
extract(month from time_id),
count(distinct user_id) users_num 
from fact_events
group by 1, 2



            --Most Lucrative Products

--You have been asked to find the 5 most lucrative products in terms of total revenue 
--for the first half of 2022 (from January to June inclusive). Output their IDs and the total revenue.

select product_id, sum(cost_in_dollars * units_sold) as revenue
from online_orders
where date between '2022-01-01' and '2022-07-01'
group by product_id
order by 2 desc
limit 5




            --Workers With The Highest Salaries

--You have been asked to find the job titles of the highest-paid employees.
--Your output should include the highest-paid title or multiple titles with the same salary.

select worker_title
from title
join worker
on worker_id = worker_ref_id
where salary = (select max(salary) from worker)


Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: