Implement windowed aggregation with multiple windows, ORDER BY ... DESC, and the RANK() function. If a window's PARTITION BY key is empty, optimize by not creating a map.