我有两张桌子第一张桌子上有一所学校和分校的部门。如果Dept
和ChildDept
值为0
,那么它就是一个部门。如果Dept
与0
不同,则它是部门的分支。 ParentDept
,Dept
和ChildDept
值与deptID
无关。他们只是按照我的理解进行练级。
表:部门
deptID ParentDept Dept ChildDept Active Department
----------+--------------+--------+-------------+------+--------
100| 1| 0| 0| 1|Education
200| 1| 1| 0| 1|Primary School
300| 1| 2| 0| 1|Primary Science
315| 2| 0| 0| 1|Arts
517| 2| 1| 0| 1|Painting
518| 2| 2| 0| 1|Music
555| 2| 3| 0| 0|Dance
第二个表包含学生信息
表:学生
studID deptID
----------+---------------
1| 300
2| 200
3| 517
4| 200
5| 300
6| 517
7| 518
我编写了一个SQL查询,可以获取每个部门的学生计数:
SELECT d.Department,
(SELECT COUNT(s.studID)
FROM Students AS s
WHERE d.deptID = s.deptID) AS studentCount,
(SELECT Department
FROM Departments
WHERE deptID = ParentDept) AS ParentDeptName
FROM Departments AS d
WHERE d.Active = 1
结果表格如下:
Department studentCount ParentDeptName
---------------+------------+--------------
Primary Science| 2|Education
Primary School | 2|Education
Painting | 2|Education
Music | 1|Education
如你所见'绘画'和音乐'分支机构属于' Arts'部门但查询结果显示'教育'对于每一行的父系都是错的。它应该像
Department studentCount ParentDeptName
---------------+------------+--------------
Primary Science| 2|Education
Primary School | 2|Education
Painting | 2|Arts
Music | 1|Arts
这个查询或我有什么问题?
答案 0 :(得分:0)
试试这个:
SELECT d.Department,
(SELECT COUNT(s.studID)
FROM Students AS s
WHERE d.deptID = s.deptID) AS studentCount,
de.Departments AS ParentDeptName
FROM Departments AS d left join Departments AS de on d.ParentDept = de.deptID
WHERE d.Active = 1
答案 1 :(得分:0)
Check Out My Fiddle我不知道我将如何计算:(
SELECT (Select Department from Departments a where a.deptID = Departments.ParentDept) As ParentDEPTS,
(Select Department from Departments b where b.deptID = Students.deptID) As StudentDEPTS, Students.studID AS STUIDS
FROM Departments
LEFT JOIN Students
ON Departments.deptID=Students.deptID
Where
Departments.ParentDept is not null
AND
Students.deptID is not null
AND
Departments.Active =1;
答案 2 :(得分:0)
让我们制作一些测试数据:
DECLARE @Dept TABLE
(
deptID INT,
ParentDept INT,
Dept INT,
ChildDept INT,
Active INT,
Department VARCHAR(50)
)
INSERT INTO @Dept
VALUES
(100, 1, 0, 0, 1, 'Education'),
(200, 1, 1, 0, 1, 'Primary School'),
(300, 1, 2, 0, 1, 'Primary Science'),
(315, 2, 0, 0, 1, 'Arts'),
(517, 2, 1, 0, 1, 'Painting'),
(518, 2, 2, 0, 1, 'Music'),
(555, 2, 3, 0, 0, 'Dance');
DECLARE @Student TABLE
(
studID INT,
deptID INT
)
INSERT INTO @Student
VALUES
(1, 300),
(2, 200),
(3, 517),
(4, 200),
(5, 300),
(6, 517),
(7, 518);
现在我们要加入学生部门,然后部门加入家长部门并将他们分组以获得我们的结果:
SELECT
d.Department,
COUNT(*) RecCnt,
p.Department ParentDept
FROM @Student s
INNER JOIN @Dept d
ON s.deptID = d.deptID
INNER JOIN @Dept p
ON p.ParentDept = d.ParentDept
AND p.Dept = 0
GROUP BY d.Department, p.Department
这是输出:
Department RecCnt ParentDept
Music 1 Arts
Painting 2 Arts
Primary School 2 Education
Primary Science 2 Education