Group-Level Filters, Self Join, STRING_AGG, Dates & CASE
Assignment review (WHERE vs HAVING), the employee-manager self join, then aggregation of strings, date functions and CASE WHEN in SQL Server.
The Crux in 60 Seconds
Group-level question, group-level filter
"Cities with no returns" or "subcategories with all three return kinds" cannot be answered row by row. LEFT JOIN, GROUP BY, then HAVING on a COUNT. A row filter in WHERE gives wrong cities.
Self join = the same table twice
Give two aliases (E1, E2) and join E1.manager_id = E2.employee_id. Take the employee name from E1 and the manager name from E2. It is not a special join type.
STRING_AGG builds lists per group
Concatenates a column's values with a separator you choose. In SQL Server, sort the list with WITHIN GROUP (ORDER BY ...).
Date functions and CASE replace manual work
DATEPART, DATEADD, DATEDIFF, DATENAME handle year, month and day boundaries. CASE tests conditions top to bottom and stops at the first match.
Foundational Concepts & Comparisons
WHERE
- Filters rows, before grouping.
- Cannot see group results such as a count per city.
HAVING
- Filters groups, after GROUP BY.
- Use when the question is about a city, subcategory or department as a whole.
INNER JOIN in Q4
- Drops department 500, because it is missing from the department table (a student saw only HR).
LEFT JOIN in Q4
- Keeps 500 with a NULL department name.
DATEPART vs DATENAME
DATEPART(month, d)returns an integer (11).DATENAME(month, d)returns the full name as a string.
IF / ELSE vs CASE
- Pure SQL has no IF/ELSE (PL/SQL does).
- Use
CASE WHEN ... THEN ... ELSE ... END. Nested CASE is possible but rarely needed.
Numeric vs text/date aggregates
- COUNT, AVG, MIN, MAX work on numbers.
- On dates and strings only MIN and MAX work; STRING_AGG joins strings.
Self join vs "another join type"
- The join kinds stay inner, left, right, full outer (plus cross). "Self join" only means the table is joined with itself.