2017-08-10 128 views
1

花费超过3小时后,我放弃了。选择总计只返回SQL Server中的一条记录

我有四个表:

Users, Approvals, Centers, Managements 

我的最终目标是让用户在用户角色分开各自管理的总数量(我有两个角色在这里:家长和社会成员)

我一直在使用下面的代码

select 
    (select count(r.StudentId) 
    from Users u 
    where u.UserId = r.StudentId and u.RoleId = 10) as Parents, 
    (select count(r.StudentId) 
    from Users u 
    where u.UserId = r.StudentId and u.RoleId = 11) as SocietyMembers, 
    e.ManagementId, e.ManagmentTitle 
from 
    CentersRegistrationsApprovals r --ON r.StudentId = u.UserId 
inner join 
    Centers c ON c.CenterId = r.CenterId 
inner join 
    Managments e ON e.ManagementId = c.EducationManagementId 
group by 
    e.ManagementId, e.ManagmentTitle, StudentId 

我期待的查询结果是因为以下几点:

Parents SocietyMambers ManagementId ManagementName 
---------------------------------------------------------------- 
3   3    10    North Region 

但结果总是被设置给了我

Parents SocietyMambers ManagementId ManagementName 
---------------------------------------------------------------- 
3   NULL    10    North Region 
NULL  3    10    North Region 

任何想法如何巩固结果只有1记录?

+5

删除组由 –

+0

@KannanKandasamy那么你不能在SELECT子句中使用它 –

回答

1

请通过studentid尝试这样的事情(未测试)

; with CTE1 as (
    select 
     (select count(r.StudentId) 
     from Users u 
     where u.UserId = r.StudentId and u.RoleId = 10) as Parents, 
     (select count(r.StudentId) 
     from Users u 
     where u.UserId = r.StudentId and u.RoleId = 11) as SocietyMembers, 
     e.ManagementId, e.ManagmentTitle 
    from 
     CentersRegistrationsApprovals r --ON r.StudentId = u.UserId 
    inner join 
     Centers c ON c.CenterId = r.CenterId 
    inner join 
     Managments e ON e.ManagementId = c.EducationManagementId 
    group by 
     e.ManagementId, e.ManagmentTitle, StudentId 
) 
SELECT MAX(Parents), MAX(SocietyMembers), ManagementId, StudentId 
FROM CTE1 
GROUP BY ManagementId, StudentId 
+0

CTE1中没有studentID结果吗?那么针对CTE1的查询不会失败? – xQbert

+0

只需从select和groupBy中删除StudentId就可以正常工作 –

2

您可以查询象下面这样:

select 
    Sum(case when u.roleId = 10 then 1 else 0 end) as Parents, 
    Sum(case when u.roleId = 11 then 1 else 0 end) as SocietyMembers, 
    e.ManagementId, e.ManagmentTitle 
from 
    CentersRegistrationsApprovals r --ON r.StudentId = u.UserId 
inner join 
    Centers c ON c.CenterId = r.CenterId 
inner join 
    Managments e ON e.ManagementId = c.EducationManagementId 
Join Users u ON r.StudentId = u.UserId 
group by 
    e.ManagementId, e.ManagmentTitle 
+0

您的解决方案正在运行,但我要彻底测试它谢谢 –