Sobes.tech
Middle

Condition There is a database with the following data schema // user id | firstname | lastname | birth 1 | Ivan | Petrov | [phone] | Anna | Petrova | [phone] | Anna | Petrova | [phone] // purchase sku | price | user_id | date 1 | 5500 | 1 | [phone] | 5700 | 1 | [phone] | 4000 | 1 | [phone] | 8000 | 2 | [phone] | 400 | 2 | [phone] // ban_list user_id | date_from 1 | [phone] You need to output: 1. Display unique combinations of user and product id for all purchases made by users before they were banned. Sort first by user name, then by SKU. 2. Find users who made purchases totaling more than 5000 rubles. Display their id, name, surname, and total purchase amount in the format id | name | surname | total amount.

sobes.tech AI

Answer from AI

For solving the SQL task:

  1. To display unique combinations of user and product id for purchases made before a ban, sorted by username and SKU:
SELECT DISTINCT u.firstname, u.lastname, p.sku
FROM purchase p
JOIN user u ON p.user_id = u.id
LEFT JOIN ban_list b ON p.user_id = b.user_id
WHERE b.date_from IS NULL OR p.date < b.date_from
ORDER BY u.firstname, p.sku;
  1. To find users whose total purchases exceed 5000, and display their id, first name, last name, and total amount:
SELECT u.id, u.firstname, u.lastname, SUM(p.price) AS total_spent
FROM user u
JOIN purchase p ON u.id = p.user_id
GROUP BY u.id, u.firstname, u.lastname
HAVING SUM(p.price) > 5000;

If you need it in Python, you can use ORM or raw SQL queries with libraries like psycopg2 or SQLAlchemy to fetch this data and display it in the desired format.