Bird
0
0

How can you combine COUNT() as a window function with a filter to count only rows where status = 'active' per department?

hard📝 Application Q9 of 15
PostgreSQL - Window Functions in PostgreSQL
How can you combine COUNT() as a window function with a filter to count only rows where status = 'active' per department?
ACOUNT(*) FILTER (WHERE status = 'active') OVER (PARTITION BY department)
BCOUNT(status = 'active') OVER (PARTITION BY department)
CCOUNT(*) OVER (PARTITION BY department WHERE status = 'active')
DCOUNT(*) OVER (FILTER WHERE status = 'active' PARTITION BY department)
Step-by-Step Solution
Solution:
  1. Step 1: Use FILTER clause inside COUNT()

    PostgreSQL supports FILTER (WHERE condition) inside aggregate and window functions to count conditionally.
  2. Step 2: Combine FILTER with window PARTITION BY

    COUNT(*) FILTER (WHERE status = 'active') OVER (PARTITION BY department) correctly applies FILTER inside COUNT() and partitions by department.
  3. Final Answer:

    COUNT(*) FILTER (WHERE status = 'active') OVER (PARTITION BY department) -> Option A
  4. Quick Check:

    FILTER clause works inside window functions [OK]
Quick Trick: Use FILTER (WHERE ...) inside COUNT() for conditional counts [OK]
Common Mistakes:
  • Placing WHERE inside OVER() instead of FILTER
  • Using COUNT() with condition inside parentheses incorrectly
  • Misordering FILTER and PARTITION BY

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes