USE shipping

---------------
-- Задание 1 --
---------------

CREATE VIEW PaymentNotifications AS
SELECT Payments.id, Customers.email, Payments.amount, Orders.date
FROM Payments
INNER JOIN Orders ON Payments.order_id = Orders.id
INNER JOIN Customers ON Orders.customer_id = Customers.id
GO

DROP VIEW PaymentNotifications
GO

-- При получении оплаты уведомлять клиентов, о начале
-- обработки заказа на указанную дату.
SELECT * FROM PaymentNotifications
GO


CREATE VIEW DeliveryExpenses AS
SELECT Deliveries.date, Vehicles.gas_consumption, Routes.distance
FROM Deliveries
INNER JOIN Vehicles ON Deliveries.vehicle_id = Vehicles.id
INNER JOIN Routes ON Deliveries.route_id = Routes.id
WHERE DATEPART(year, date) = DATEPART(year, GETDATE())
GO

DROP VIEW DeliveryExpenses
GO

-- Посчитать затраты на топливо по месяцам в текущем году.
SELECT DATEPART(month, date), SUM(gas_consumption * distance)
FROM DeliveryExpenses
GROUP BY DATEPART(month, date)
GO


CREATE VIEW BoxDates AS
SELECT Boxes.id, Orders.id, Deliveries.date
FROM Shipments
INNER JOIN Orders ON Shipments.order_id = Orders.id
INNER JOIN Boxes ON Orders.id = Boxes.order_id
INNER JOIN Deliveries ON Shipments.delivery_id = Deliveries.id
WHERE Deliveries.date > GETDATE()
GO

DROP VIEW BoxDates
GO

-- Найти даты доставки всех недоставленных коробок.
SELECT * FROM Boxes
GO

---------------
-- Задание 2 --
---------------

CREATE VIEW BoxesView AS
SELECT * FROM shipping.dbo.Boxes
WHERE weight < 25 AND volume <= 1.1
WITH CHECK OPTION
GO

DROP VIEW BoxesView
GO

INSERT INTO BoxesView (order_id, warehouse_id, wrapping_id, volume, weight)
VALUES (1, 1, 1, 0.7, 13)
GO

INSERT INTO BoxesView (order_id, warehouse_id, wrapping_id, volume, weight)
VALUES (1, 1, 1, 1.7, 13)
GO

INSERT INTO BoxesView (order_id, warehouse_id, wrapping_id, volume, weight)
VALUES (1, 1, 1, 0.5, 27)
GO

---------------
-- Задание 3 --
---------------

SET NUMERIC_ROUNDABORT OFF;
SET ANSI_PADDING, ANSI_WARNINGS,
    CONCAT_NULL_YIELDS_NULL, ARITHABORT,
    QUOTED_IDENTIFIER, ANSI_NULLS ON;
GO

CREATE VIEW [dbo].[PaymentNotificationsInd] WITH SCHEMABINDING AS
SELECT Payments.id, Customers.email, Payments.amount, Orders.date
FROM [dbo].[Payments]
INNER JOIN [dbo].[Orders] ON Payments.order_id = Orders.id
INNER JOIN [dbo].[Customers] ON Orders.customer_id = Customers.id
GO

DROP VIEW PaymentNotificationsInd
GO

CREATE UNIQUE CLUSTERED INDEX NotifyEmail
ON PaymentNotificationsInd (id, email)
GO

DROP INDEX NotifyEmail ON PaymentNotificationsInd
GO

SELECT * FROM PaymentNotificationsInd
GO

SELECT Payments.id, Customers.email, Payments.amount, Orders.date
FROM [dbo].[Payments]
INNER JOIN [dbo].[Orders] ON Payments.order_id = Orders.id
INNER JOIN [dbo].[Customers] ON Orders.customer_id = Customers.id
GO