Here's an example of a complex SQL query that uses a variety of advanced features:
WITH recursive cte AS (
SELECT employer_id, employee_name, manager_id, 1 as depth
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.employer_id, e.employee_name, e.manager_id, cte.depth + 1
FROM employees e
JOIN cte ON e.manager_id = cte.employee_id
),
cte2 AS (
SELECT employer_id,
employee_name,
manager_id,
depth,
DENSE_RANK() OVER (ORDER BY depth DESC) as rank
FROM cte
),
cte3 AS (
SELECT employer_id,
employee_name,
manager_id,
depth,
rank,
LAG(rank) OVER (ORDER BY depth DESC) as prev_rank
FROM cte2
),
cte4 AS (
SELECT employer_id,
employee_name,
manager_id,
depth,
rank,
prev_rank,
CASE
WHEN rank = prev_rank + 1 THEN 'same level'
WHEN rank = prev_rank - 1 THEN 'promotion'
ELSE 'demotion'
END as promotion_status
FROM cte3
)
SELECT employer_id,
employee_name,
manager_id,
depth,
rank,
STRING_AGG(promotion_status, ',') WITHIN GROUP (ORDER BY depth DESC) as promotion_history
FROM cte4
GROUP BY 1,2,3,4,5
ORDER BY 1,2,3,4,5;
This query uses a recursive common table expression (CTE) to build a hierarchical organization chart from the employees table. It then uses window functions (DENSE_RANK, LAG) to calculate the level and promotion history for each employee, and finally uses string aggregation (STRING_AGG) to summarize the promotion history for each employee.
This query is quite complex, and relies on several advanced SQL features, including:
- Recursive common table expressions (CTEs)
- Window functions (
DENSE_RANK, LAG)
- String aggregation (
STRING_AGG)
- Conditional logic (
CASE statement)
- Grouping and ordering (
GROUP BY, ORDER BY)
Please note that this query is written for PostgreSQL, and some of the features used in the query may not be available in other SQL dialects.