带有SQL Server 2005数据库的SQL Server 2008 R2 SMS
搜索,但无济于事。我想在每一行的末尾寻找所有员工的总数。我可以得到每个经理的计数,这很好。但是,我需要员工总数中的另一列进行进一步计算。
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
我期待或试图达到这样的目标
Manager EmployeeCount Terminations TotalEmployees
=============================================================='
boss 1 0 4
man 2 2 4
vp 1 1 4
到目前为止,这是我的代码。我想我需要在那里包装一个select语句来获得行尾的员工总数,但我无法弄清楚语法或者是否在where语句之后。另外,如果下面的代码有点失误,我很抱歉,我试图从我拥有的其他行(连接等)中解析它。
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
感谢您的帮助。
答案 0 :(得分:2)
您可以使用窗口功能执行此操作。窗口函数可以嵌套在聚合中,因此:
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;
我认为您COUNT(DISTINCT)
不需要EmployeeCount
,所以我删除了DISTINCT
。
答案 1 :(得分:0)
WITH ROLLUP修改器也会为您提供所需的内容。
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