Files
homework/ebelykh/postgresql/агрегации и группировки/агрегации.sql
T

72 lines
1.8 KiB
SQL
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
--Задача 1
В варианте А: WHERE фильтрует товары и убирает те, которые не в наличии, потом эти товары(строки)участвуют в группировке, в варианте В - HAVING фильтрует уже сгруппированные данные(категории)
--Задача 2356
SELECT teacher_id,
COUNT(DISTINCT subject_id) AS cnt
FROM teacher
GROUP BY teacher_id;
--Задача 1581
SELECT customer_id,
COUNT(v.visit_id) AS count_no_trans
FROM visits v
LEFT JOIN transactions t
ON v.visit_id = t.visit_id
WHERE t.transaction_id IS NULL
GROUP BY customer_id;
--Задача 1141
SELECT activity_date AS day,
COUNT(DISTINCT user_id) AS active_users
FROM Activity
WHERE activity_date BETWEEN '2019-06-28' AND '2019-07-27'
GROUP BY activity_date;
--Задача 596
SELECT class
FROM Courses
GROUP BY class
HAVING COUNT(student) >= 5;
--Задача 1075
SELECT project_id,
ROUND(AVG(experience_years), 2) AS average_years
FROM Project p
JOIN Employee e
ON p.employee_id = e.employee_id
GROUP BY project_id;
--Задача 1729
SELECT user_id,
COUNT (follower_id) AS followers_count
FROM followers
GROUP BY user_id
ORDER BY user_id;
--Задача 1633
SELECT
r.contest_id,
ROUND(
COUNT(r.user_id) * 100.0 / (SELECT COUNT(*) FROM Users),
2
) AS percentage
FROM Register r
GROUP BY r.contest_id
ORDER BY percentage DESC, r.contest_id ASC;
--Задача 1251
SELECT
p.product_id,
COALESCE(
ROUND(
SUM(u.units * p.price) * 1.0 / NULLIF(SUM(u.units), 0),
2
),
0
) AS average_price
FROM Prices p
LEFT JOIN UnitsSold u
ON p.product_id = u.product_id
AND u.purchase_date BETWEEN p.start_date AND p.end_date
GROUP BY p.product_id;