Question

SQL Server 2008 R2 SMS with a SQL Server 2005 database

Searching, but to no avail. I'm looking for a grand total of all employees at the end of each row. I can get the counts for each manager, that works fine. However, I need another column of the total number of employees for further calculations.

 Manager       IndID         HireDate           TermDate
=========      ======        ==========         ==========  
boss           EMP1          2013-01-02         
man            EMP2          2013-10-02         2014-03-06
man            EMP2          2013-04-02         2014-01-01
vp             EMP3          2012-05-02         2013-06-15  

I'm expecting or trying to get to something like this

Manager      EmployeeCount     Terminations    TotalEmployees
=============================================================='
boss          1                0               4
man           2                2               4
vp            1                1               4

So far, here is the code I have. I figure I need to wrap a select statement in there to get the grand total of employees at the end of the row, but I cannot figure out the syntax or if it goes after the where statement. Also, I apologize if the code below is a bit off, I tried to parse it down from the other lines I have (joins and such).

SELECT  
   Manager
   , COUNT (DISTINCT IndID) EmployeeCount
   , SUM(CASE WHEN TermDate BETWEEN @StartDate AND @EndDate THEN 1 ELSE 0 END) Terminations
FROM 
   myTable 
WHERE 
   HireDate <= @EndDate 
   AND TermDate BETWEEN @StartDate AND @EndDate
    OR StartDate <= @EndDate AND TermDate IS NULL
GROUP BY 
   Manager

Thanks for all the help.

Était-ce utile?

La solution

You can do this using window functions. Window functions can be nested in aggregations, so:

SELECT  Manager,
        COUNT(IndID) as EmployeeCount,
        SUM(CASE WHEN TermDate BETWEEN @StartDate AND @EndDate THEN 1 ELSE 0 END) as Terminations,
        SUM(COUNT(*)) OVER () as TotalEmployees
FROM myTable 
WHERE HireDate <= @EndDate AND TermDate BETWEEN @StartDate AND @EndDate OR
      StartDate <= @EndDate AND TermDate IS NULL
GROUP BY Manager;

I didn't think you needed COUNT(DISTINCT) for EmployeeCount, so I removed the DISTINCT.

Autres conseils

The WITH ROLLUP modifier will give you what you want, as well.

http://technet.microsoft.com/en-us/library/ms189305(v=sql.90).aspx

SELECT Manager
, COUNT (DISTINCT IndID) EmployeeCount
, SUM(CASE WHEN TermDate BETWEEN @StartDate AND @EndDate THEN 1 ELSE 0 END) Terminations
FROM myTable 
WHERE HireDate <= @EndDate AND TermDate BETWEEN @StartDate AND @EndDate
               OR StartDate <= @EndDate AND TermDate IS NULL
GROUP BY Manager WITH ROLLUP
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top