9. Filter, Then Compare Within a CTE
MediumCTEsCTE filteringself-reference for aggregate
A CTE can be filtered, then the outer query can reference an aggregate computed over that same filtered set — a clean two-step that avoids repeating the filter.
Task: from products, consider only items that are in stock
(stock > 0). Among those, return the ones whose price is above the average
price of the in-stock items. Return name and price, ordered by price
descending.
Tables
Loading schema…
Expected outputrows must come back in this order
Computing expected output…
This is the result for the example data above. On Submit your query is graded against this example plus 4 hidden edge cases — 5test cases in all. A sloppy query that only fits the example won't pass.
SQL· SQLite · runs in your browser
⌘/Ctrl+↵ run · ⇧⌘/Ctrl+↵ submit
Run a query to see its output here.