| 7 | |
| 8 | {{{ |
| 9 | CREATE FUNCTION GetCustomerShipmentsReport(month INT, year INT) |
| 10 | RETURNS TABLE( |
| 11 | CustomerName varchar(50), |
| 12 | CustomerTypeName varchar(50), |
| 13 | TotalWineQuantity bigint, |
| 14 | TotalWineProfit double precision, |
| 15 | TotalWineBasePrice double precision, |
| 16 | TotalWineAgreedPrice double precision, |
| 17 | PercentageDifference double precision |
| 18 | ) |
| 19 | LANGUAGE plpgsql |
| 20 | AS $$ |
| 21 | BEGIN |
| 22 | RETURN QUERY |
| 23 | SELECT |
| 24 | c.customer_name as CustomerName, |
| 25 | ct.customer_type_name as CustomerTypeName, |
| 26 | SUM(wine_quantity) AS TotalWineQuantity, |
| 27 | SUM(wine_base_price * wine_quantity) AS TotalWineBasePrice, |
| 28 | SUM(wine_agreed_price * wine_quantity) AS TotalWineAgreedPrice, |
| 29 | SUM((wine_agreed_price * wine_quantity) - (wine_base_price * wine_quantity)) as TotalWineProfit, |
| 30 | (SUM((wine_agreed_price * wine_quantity) - (wine_base_price * wine_quantity)) / SUM(wine_base_price * wine_quantity)) * 100 as PercentageDifference |
| 31 | FROM shipment_load sl |
| 32 | join customer c on c.customer_id = sl.customer_id |
| 33 | join customer_type ct on c.customer_type_id = ct.customer_type_id |
| 34 | JOIN shipment s ON sl.shipment_id = s.shipment_id |
| 35 | WHERE EXTRACT(MONTH FROM s.shipment_date) = month AND EXTRACT(YEAR FROM s.shipment_date) = year |
| 36 | GROUP BY c.customer_name, ct.customer_type_name |
| 37 | order by SUM((wine_agreed_price * wine_quantity) - (wine_base_price * wine_quantity)) desc; |
| 38 | END; |
| 39 | $$; |
| 40 | }}} |
| 41 | |