95 lines
2.2 KiB
Markdown
95 lines
2.2 KiB
Markdown
## Lecture 1 (13:00) - Sub-queries
|
|
|
|
- Aggregate functions cannot be used in a where clause.
|
|
ex.
|
|
|
|
```sql
|
|
SELECT staffNo, name, position, salary
|
|
FROM staff
|
|
WHERE salary > ( SELECT AVG(salary) FROM STAFF )
|
|
```
|
|
|
|
### IN Operator
|
|
|
|
- Used to check if an attribute has a value from a set of values.
|
|
- \[NOT] IN (\<value list>)
|
|
ex.
|
|
|
|
```sql
|
|
SELECT name
|
|
FROM Drivers
|
|
WHERE address IN ("Dundee", "Aberdeen")
|
|
```
|
|
|
|
ex of IN used with subqueries. This would select all properties, their rooms and rent values, where their staff number matches a specific branch number
|
|
|
|
```sql
|
|
SELECT propertyNo, rooms, rent
|
|
FROM property
|
|
WHERE staffNo IN
|
|
( SELECT staffNo
|
|
FROM staff
|
|
WHERE branchNo = (
|
|
SELECT branchNo
|
|
FROM branch
|
|
WHERE street = "Main St"
|
|
)
|
|
);
|
|
```
|
|
|
|
## Tutorial 2 (15:00) - SQL Sub-queries
|
|
|
|

|
|

|
|
|
|
1. List the names of pirates who have pillaged booty of type bt3.
|
|
|
|
```sql
|
|
SELECT p-name
|
|
FROM pirates
|
|
WHERE p-code IN (
|
|
SELECT p-code
|
|
FROM pillage
|
|
WHERE boat-code = "b3"
|
|
)
|
|
);
|
|
```
|
|
|
|
1. List the names of pirates who have pillaged any kind of fruit.
|
|
|
|
```sql
|
|
SELECT p-name
|
|
FROM pirates
|
|
WHERE p-code IN (
|
|
SELECT p-code
|
|
FROM pillage
|
|
WHERE booty-code IN (
|
|
SELECT booty-code
|
|
FROM booty
|
|
WHERE booty-name LIKE "%Fruit"
|
|
)
|
|
);
|
|
```
|
|
|
|
1. List the names of booty whose value is greater than the average value of all the booty.
|
|
|
|
```sql
|
|
SELECT booty-name
|
|
FROM booty
|
|
WHERE value > (
|
|
SELECT AVG(value)
|
|
FROM booty
|
|
);
|
|
```
|
|
|
|
## Workshop 2 (10:00)
|
|
|
|
1. List the names of the products whose number of units on order is greater than the average number of units in stock.
|
|

|
|
|
|
2. List the names of the products which have a value for UnitsInStock that is less than the average number of units in stock. Your query should also list the value for the UnitsInStock for each of these products. The results must be sorted into ascending order on UnitsInStock.
|
|

|
|
|
|
3. List names of the products whose number of units in stock is less than the average number of units in stock and whose number of units on order is less than the average number of units on order.
|
|
|
|
 |