This repository has been archived by the owner on Jan 6, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathQ4.sql
44 lines (44 loc) · 2.05 KB
/
Q4.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
SELECT loss.customercategoryname,
loss.maxloss,
T2.customername,
T2.customerid
FROM (SELECT T1.customercategoryname,
Max(T1.totalvaluelostorders) AS MaxLoss
FROM (SELECT Cu.customerid,
Cu.customername,
Ca.customercategoryname,
Sum(ol.quantity * ol.unitprice) AS TotalValueLostOrders
FROM sales.orders AS O,
sales.orderlines AS ol,
sales.customers AS Cu,
sales.customercategories AS Ca
WHERE NOT EXISTS (SELECT *
FROM sales.invoices AS I
WHERE I.orderid = O.orderid)
AND ol.orderid = O.orderid
AND Cu.customerid = O.customerid
AND Ca.customercategoryid = Cu.customercategoryid
GROUP BY Cu.customerid,
Cu.customername,
Ca.customercategoryname) AS T1
GROUP BY customercategoryname) AS loss,
(SELECT Cu.customerid,
Cu.customername,
Ca.customercategoryname,
Sum(ol.quantity * ol.unitprice) AS TotalValueLostOrders
FROM sales.orders AS O,
sales.orderlines AS ol,
sales.customers AS Cu,
sales.customercategories AS Ca
WHERE NOT EXISTS (SELECT *
FROM sales.invoices AS I
WHERE I.orderid = O.orderid)
AND ol.orderid = O.orderid
AND Cu.customerid = O.customerid
AND Ca.customercategoryid = Cu.customercategoryid
GROUP BY Cu.customerid,
Cu.customername,
Ca.customercategoryname) AS T2
WHERE loss.customercategoryname = T2.customercategoryname
AND loss.maxloss = T2.totalvaluelostorders
ORDER BY loss.maxloss DESC