-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathview with CTE.sql
62 lines (50 loc) · 1.93 KB
/
view with CTE.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
------------------VIEW------------------------------------------------------------
--"AS a CEO of this company I would like to know what are the basic statistics (average, sum, count, ranks) for our
--shops, to make further business decisions based on that"
--" I would also like to know which three shops have the highest total sales"
----------------------------------------------------------------------------------
--window functions used inside the view---
---based on previous view I have create a ranking of 3 shops with highes sales sum
CREATE VIEW vSalesOfProductsByShops
AS
WITH Base AS
(SELECT apc.Name AS Shop,
p.ProductName,
p.SellPrice AS Price,
SUM(dl.Quantity) AS QuantityOfProduct,
SUM(dl.Quantity*p.SellPrice) AS TotalAmount
FROM DocumentHeaders dh
INNER JOIN DocumentLines dl
ON dh.ID = dl.DocumentHeaderID
INNER JOIN AssociatedPlaces apc
ON apc.ID = dh.OriginalPlaceID
INNER JOIN Products p
On p.ID = dl.ProductID
WHERE DocumentType = 'Receipt'
GROUP BY apc.Name,
p.ProductName,
p.SellPrice
)
SELECT
Shop,
ProductName,
Price,
QuantityOfProduct,
TotalAmount,
AVG(TotalAmount) OVER (Partition BY Shop ORDER BY TotalAmount
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS AverageSales,
COUNT(TotalAmount) OVER (Partition BY Shop ORDER BY TotalAmount
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS CountSales,
SUM(TotalAmount) OVER (Partition BY Shop ORDER BY TotalAmount
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS SumSales,
RANK() OVER (Partition BY Shop ORDER BY TotalAmount desc) AS RankNumber,
DENSE_RANK() OVER (Partition BY Shop ORDER BY TotalAmount desc) AS DenseRankNumber
FROM Base
CREATE VIEW vSumSalesTop3Shops
AS
SELECT TOP 3 Shop, SumSales
FROM vSalesOfProductsByShops
GROUP BY Shop, SumSales
ORDER BY SumSales desc
SELECT * FROM vSalesOfProductsByShops
SELECT * FROM vSumSalesTop3Shops