SQL Server基础知识 - where子句

时间:2016-02-06 17:57:49

标签: sql sql-server tsql

这是我的代码:

use TSQL2012

select 
    emp.empid, emp.firstname, emp.mgrid, 
    manager.firstname as manager_name,
    sum(unique(emp.mgrid)) as Total
from 
    HR.Employees AS emp, HR.Employees as manager
where 
    emp.mgrid = manager.empid
go

我应该得到的结果是:

   empid firstame mgrid manager_name Total
1   2   Don        1    Sara          1
2   3   Judy       2    Don           2
3   4   Yael       3    Judy          2
4   5   Sven       2    Don           2
5   6   Paul       5    Sven
6   7   Russell    5    Sven
7   8   Maria      3    Judy
8   9   Zoya       5    Sven

我无法获得最后一栏(总计)。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

这样做的一种方法是使用CROSS APPLY

select emp.empid, emp.firstname, emp.mgrid, manager.firstname as manager_name, 
       x.cnt as Total
from Employees AS emp
inner join Employees as manager on emp.mgrid = manager.empid
cross apply (
   select count(*)
   from Employees AS e
   where e.mgrid = emp.mgrid) AS x(cnt) 

Demo here

修改

您也可以这样使用CTE

;With C as ( 
   select b.mgrid, count(*) as Total 
   from Employees as b 
   group by mgrid 
) 
select emp.empid, emp.firstname, emp.mgrid, manager.firstname as manager_name, 
       Total 
from Employees AS emp
inner join Employees as manager on emp.mgrid = manager.empid
inner join C on emp.mgrid = C.mgrid

Demo here