Monday, August 10, 2026

171 ) 12 . show team size of each employee in the query result

 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

12 .  show team  size of  each employee in the query result 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Employee Table:

+-------------+------------+

| employee_id | team_id    |

+-------------+------------+

|     1       |     8      |

|     2       |     8      |

|     3       |     7      |

+-------------+------------+

Result table:

+-------------+------------+

| employee_id | team_size  |

+-------------+------------+

|     1       |     3      |

|     2       |     3      |

|     3       |     3      |

 


---------------------------------------------------------------------------------------------------

Method 1: Using a Window Function (Recommended & Cleanest)

SQL
SELECT 
    employee_id, 
    COUNT(*) OVER (PARTITION BY team_id) AS team_size
FROM 
    Employee;


Method 2: Using a Subquery (Without Window Functions)

SQL
SELECT 
    e1.employee_id,
    (
        SELECT COUNT(*) 
        FROM Employee e2 
        WHERE e2.team_id = e1.team_id
    ) AS team_size
FROM 
    Employee e1;


No comments:

Post a Comment

239 ) Metadata Management

Metadata Management and Modern Data Governance Tools Metadata management forms the backbone of data governance, data lineage, and data quali...