Skip to content

Instantly share code, notes, and snippets.

@SlavikArt
Created January 22, 2024 13:02
Show Gist options
  • Save SlavikArt/ea28d5b8da3bcdb429735ee86fa0d01e to your computer and use it in GitHub Desktop.
Save SlavikArt/ea28d5b8da3bcdb429735ee86fa0d01e to your computer and use it in GitHub Desktop.

Subquerries (on Product)

Subquerries

-- 1. Определить, сколько товаров в процентном соотношении
-- делает тот или иной производитель
-- Применить подзапрос в предложении SELECT
SELECT
Producer.name AS 'producer',
CAST((
SELECT COUNT(*)
FROM Product
WHERE id_producer = Producer.id
) AS float) / (SELECT COUNT(*) FROM Product) * 100 AS '%'
FROM Producer
ORDER BY Producer.name
-- 2. Показать всех производителей,
-- товары которых продавались более 3 раз
SELECT Producer.name AS 'producer'
FROM Producer
WHERE (
SELECT COUNT(*)
FROM Sale
WHERE id_product IN (
SELECT id
FROM Product
WHERE id_producer = Producer.id
)
) > 3
-- 3. Показать самый популярный товар магазина
-- (больше всего раз продавался)
SELECT Product.name AS 'product'
FROM Product
WHERE Product.id IN (
SELECT TOP 1 id_product
FROM Sale
GROUP BY id_product
ORDER BY COUNT(id_product) DESC
)
-- 4. Показать названия поставщиков,
-- которые никогда не поставляли йогурт
SELECT Supplier.name AS 'supplier'
FROM Supplier
WHERE Supplier.id IN (
SELECT id_supplier
FROM Delivery
WHERE Delivery.id_product IN (
SELECT id
FROM Product
WHERE Product.name NOT LIKE 'Yogurt'
)
)
-- 5. Показать на экран список производителей,
-- которые живут в той же стране,
-- что и фирма ООО "Зеленоглазое такси"
SELECT Producer.name AS 'producer'
FROM Producer
WHERE (
SELECT id_country
FROM Region
WHERE id = (
SELECT id_region
FROM City
WHERE id = (
SELECT id_city
FROM Address
WHERE id = Producer.id_address
)
)
) = (
SELECT id_country
FROM Region
WHERE id = (
SELECT id_region
FROM City
WHERE id = (
SELECT id_city
FROM Address
WHERE id = (
SELECT id_address
FROM Producer
WHERE name = 'OOO Zelenoglazoe taksi'
)
)
)
)
EXCEPT
SELECT Producer.name
FROM Producer
WHERE name = 'OOO Zelenoglazoe taksi'
-- 6. Показать всех производителей, количество наименований
-- товаров которых в магазине больше, чем количество наименований
-- всех товаров фирмы ООО "Самтаймс"
SELECT Producer.name AS 'producer'
FROM Producer
WHERE (
SELECT COUNT(*)
FROM Product
WHERE Product.id_producer = Producer.id
) > (
SELECT COUNT(*)
FROM Product
WHERE id_producer IN (
SELECT id
FROM Producer
WHERE name = 'OOO Samtaims'
)
)
-- 7. Показать общее количество продаж по каждому дню,
-- начиная от 15.11.2023, и по сей день.
-- Отсортировать по убыванию даты
SELECT
Sale.date_of_sale,
SUM(Sale.quantity) AS 'sales_quantity'
FROM Sale
WHERE Sale.date_of_sale BETWEEN '2023-11-15' AND GETDATE()
GROUP BY Sale.date_of_sale
ORDER BY Sale.date_of_sale DESC
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment