-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2.2 Common Table Expression
72 lines (66 loc) · 1.34 KB
/
2.2 Common Table Expression
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
--Retrieving all orders along with customer and plant details
WITH OrderDetails AS (
SELECT
o.orderid,
o.orderdate,
c.customername,
p.name AS plantname,
o.quantity
FROM
Orders o
INNER JOIN
Customers c ON o.customerid = c.customerid
INNER JOIN
Plants p ON o.plantid = p.plantid
)
SELECT * FROM OrderDetails;
--Calculating total sales for each customer
WITH CustomerSales AS (
SELECT
c.customerid,
c.customername,
SUM(o.quantity * p.price) AS total_sales
FROM
Customers c
INNER JOIN
Orders o ON c.customerid = o.customerid
INNER JOIN
Plants p ON o.plantid = p.plantid
GROUP BY
c.customerid,
c.customername
)
SELECT * FROM CustomerSales;
--Retrieving top 5 customers
WITH TopCustomers AS (
SELECT TOP 5
c.customerid,
c.customername,
SUM(o.quantity) AS totalquantity
FROM
Customers c
INNER JOIN
Orders o ON c.customerid = o.customerid
GROUP BY
c.customerid,
c.customername
ORDER BY
SUM(o.quantity) DESC
)
SELECT * FROM TopCustomers;
--Sales for each plant
WITH PlantSales AS (
SELECT
p.plantid,
p.name AS plantname,
SUM(o.quantity) AS totalquantity,
SUM(o.quantity * p.price) AS totalsales
FROM
Plants p
INNER JOIN
Orders o ON p.plantid = o.plantid
GROUP BY
p.plantid,
p.name
)
SELECT * FROM PlantSales;