[英]How to SELECT Parent and Child Categories with One Query?
我有兩張桌子第一張桌子擁有學校和分支機構的部門。 如果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
如您所見,“繪畫”和“音樂”分支屬於“藝術”部門,但查詢結果顯示每一行的父部門的“教育”,這是錯誤的。 應該像
Department studentCount ParentDeptName
---------------+------------+--------------
Primary Science| 2|Education
Primary School | 2|Education
Painting | 2|Arts
Music | 1|Arts
這個查詢或我怎么了?
試試這個:
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
簽出我的小提琴,我不知道我要怎么數:(
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;
讓我們做一些測試數據:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.