2017-08-10 126 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

您的解決方案正在運行,但我要徹底測試它謝謝 –