Refine organization query to count only active members using CASE statement

This commit is contained in:
Felipe Cardoso
2025-11-06 11:11:18 +01:00
parent 9c72fe87f9
commit dde091138e

View File

@@ -4,7 +4,7 @@ import logging
from typing import Optional, List, Dict, Any from typing import Optional, List, Dict, Any
from uuid import UUID from uuid import UUID
from sqlalchemy import func, or_, and_, select from sqlalchemy import func, or_, and_, select, case
from sqlalchemy.exc import IntegrityError from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
@@ -149,15 +149,16 @@ class CRUDOrganization(CRUDBase[Organization, OrganizationCreate, OrganizationUp
""" """
try: try:
# Build base query with LEFT JOIN and GROUP BY # Build base query with LEFT JOIN and GROUP BY
# Use CASE statement to count only active members
query = ( query = (
select( select(
Organization, Organization,
func.count( func.count(
func.distinct( func.distinct(
and_( case(
UserOrganization.is_active == True, (UserOrganization.is_active == True, UserOrganization.user_id),
UserOrganization.user_id else_=None
).self_group() )
) )
).label('member_count') ).label('member_count')
) )