Skip to content

Commit 2feab35

Browse files
authored
Cover CTE's
1 parent a825458 commit 2feab35

File tree

1 file changed

+28
-3
lines changed

1 file changed

+28
-3
lines changed

advanced_sql_class_notes.md

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -539,7 +539,32 @@ WHERE ORDER_DATE BETWEEN '2017-03-26' AND '2017-03-31'
539539
GROUP BY 1,2,3,4,5,6,7,8
540540
```
541541

542-
## 4.5 Self Joins
542+
543+
## 4.5 Common Table Expressions
544+
545+
Similiar to temporary tables, you can actually create Common Table Expressions to "re-use" one or more derived tables. You can certainly use temporary tables instead, but if you don't want to persist and save the data, common table expressions can be helpful to simply provide names to derived tables. This way you can simplify your queries greatly.
546+
547+
For instance, we can create two derived tables "TX_CUSTOMERS" and "TX_ORDERS" but give them names as common table expressions. Then we can proceed to use those two derived tables like this.
548+
549+
```sql
550+
551+
WITH TX_CUSTOMERS AS
552+
(
553+
SELECT * FROM CUSTOMER
554+
WHERE STATE = 'TX'
555+
),
556+
557+
TX_ORDERS AS
558+
(
559+
SELECT * FROM CUSTOMER_ORDER
560+
WHERE CUSTOMER_ID IN (SELECT CUSTOMER_ID FROM TX_CUSTOMERS)
561+
)
562+
563+
SELECT * FROM TX_ORDERS INNER JOIN TX_CUSTOMERS
564+
ON TX_ORDERS.CUSTOMER_ID = TX_CUSTOMERS.CUSTOMER_ID
565+
```
566+
567+
## 4.6 Self Joins
543568
544569
We can join a table to itself by invoking it twice with two aliases. This can be useful, for example, to look up the previous day's order quantity (if any) for a given `CUSTOMER_ID` and `PRODUCT_ID`:
545570

@@ -582,7 +607,7 @@ QUANTITY,
582607
FROM CUSTOMER_ORDER c1
583608
```
584609

585-
## 4.6 Cross Joins
610+
## 4.7 Cross Joins
586611

587612
Sometimes it can be helpful to generate a "cartesian product", or every possible combination between two or more data sets using a CROSS JOIN. This is often done to generate a data set that fills in gaps for another query. Not every calendar date has orders, nor does every order date have an entry for every product, as shown in this query:
588613

@@ -652,7 +677,7 @@ ORDER BY CALENDAR_DATE, all_combos.PRODUCT_ID
652677
```
653678

654679

655-
## 4.7 Comparative Joins
680+
## 4.8 Comparative Joins
656681

657682
Note also you can use comparison operators in joins. For instance, we can self-join to create rolling quantity totals and generate a cartesian product on previous dates to the current order, and then sum those quantities. It is much easier to use windowing functions for this purpose though, which is covered in the next section.
658683

0 commit comments

Comments
 (0)