Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

1

Database design
Belgium Campus – DBD2x1 – lesson 19

©©BELGIUM
BELGIUMCAMPUS
CAMPUS2021
2021
2

Common Table Expressions

© BELGIUM CAMPUS 2021


3

Common WITH TitleCount (authorID, titleCount) AS


(
table SELECT au_id, COUNT(title_id)

expressions FROM titleauthor


GROUP BY au_id
)

SELECT au_id, au_lname, au_fname, titleCount


FROM authors a
INNER JOIN TitleCount
ON TitleCount.authorID = a.au_id

© BELGIUM CAMPUS 2021


4

WITH GhostTableName We always define a proper name for this table.

Common (Col1, Col2) One of the columns needs to be an ID to link to other tables.

table AS This specifies the body of the CTE.

( This SELECT is used to give the CTE its data.


expressions SELECT Col1ID, SUM(Col2) Must contain same number of columns as defined.

FROM Table

GROUP BY Col1ID

SELECT Columns This is the display.

FROM Table

INNER JOIN CTE

ON Table.ID = CTE.Col1

© BELGIUM CAMPUS 2021


5

WITH ProductSold (ProductID, TotalSold)

Common AS

table (

SELECT ProductID, SUM(OrderQty)


expressions FROM Sales.SalesOrderDetail

GROUP BY ProductID

SELECT p.ProductID, p.Name, p.ProductNumber, ps.TotalSold

FROM Production.Product AS p

INNER JOIN ProductSold AS ps

ON p.ProductID = ps.ProductID

© BELGIUM CAMPUS 2021


6
WITH Cost (ProductID, AvgCost)
AS
Common (SELECT ProductID, AVG(StandardCost)
FROM Production.ProductCostHistory

table GROUP BY ProductID),

expressions Sold (ProductID, AvgSold)


AS
(SELECT ProductID, AVG(OrderQty)
FROM Sales.SalesOrderDetail
GROUP BY ProductID)

SELECT p.ProductID, p.Name,


(AvgCost * AvgSold)AS TotalCost
FROM Sold s
INNER JOIN Production.Product p
ON s.ProductID = p.ProductID
INNER JOIN Cost c
ON p.ProductID = c.ProductID

© BELGIUM CAMPUS 2021


WITH Cost (ProductID, AvgCost) 7
AS
(SELECT ProductID, AVG(StandardCost)

Common FROM Production.ProductCostHistory


GROUP BY ProductID),

table Sold (ProductID, AvgSold)


AS
expressions (SELECT ProductID, AVG(OrderQty)
FROM Sales.SalesOrderDetail
GROUP BY ProductID),

Total (ProductID, TotalCost)


AS
(SELECT c.ProductID, (AvgCost * AvgSold)
FROM Cost c
INNER JOIN Sold s
ON c.ProductID = s.ProductID)

SELECT p.ProductID, p.Name, t.TotalCost


FROM Production.Product p
INNER JOIN Total t
ON p.ProductID = t.ProductID
© BELGIUM CAMPUS 2021

You might also like