You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: advanced_sql_class_notes.md
+28-3Lines changed: 28 additions & 3 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -539,7 +539,32 @@ WHERE ORDER_DATE BETWEEN '2017-03-26' AND '2017-03-31'
539
539
GROUP BY 1,2,3,4,5,6,7,8
540
540
```
541
541
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
543
568
544
569
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`:
545
570
@@ -582,7 +607,7 @@ QUANTITY,
582
607
FROM CUSTOMER_ORDER c1
583
608
```
584
609
585
-
## 4.6 Cross Joins
610
+
## 4.7 Cross Joins
586
611
587
612
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:
588
613
@@ -652,7 +677,7 @@ ORDER BY CALENDAR_DATE, all_combos.PRODUCT_ID
652
677
```
653
678
654
679
655
-
## 4.7 Comparative Joins
680
+
## 4.8 Comparative Joins
656
681
657
682
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.
0 commit comments