SQL time-space assignment
When SQL makes statistical queries, it is often necessary to count the total number of another field after grouping. This is often the case where the COUNT (field to be counted) result is NULL. If you directly send the result NULL to the caller, the other party will be difficult to deal with. So we need to judge the outgoing: if it is empty, then pass 0.
To achieve this function, you can use the ISNULL function.
Function calling method
ISNULL (the value that needs to be judged to be empty, and the value to be returned when judged to be empty)
Call example
Table Class (AID, class name, class teacher name)
AID | Name | HeadTeacher |
---|---|---|
1 | Grade One | …… |
2 | Grade one and grade two | …… |
3 | Grade One Three | …… |
4 | High school first class | …… |
Table Student (AID, student name, class)
AID | Name | ClassAID |
---|---|---|
1 | Zhang San | 1 |
2 | Li Si | 1 |
3 | Wang Wu | 1 |
4 | Zhang San | 2 |
5 | Li Si | 2 |
6 | Wang Wu | 2 |
7 | Zhao Liu | 2 |
Obviously, the ClassAID field of the Student table is referenced from the AID field of the Class table to indicate which class this student belongs to
--这是一个统计查询:查询各个班都分别有多少学生
SELECT
[ClassAID] = C.AID
,[StudentNumber] = COUNT(S.AID)
FROM Class AS C
JOIN Student AS S ON S.ClassAID = C.AID
GROUP BY C.AID
--上面这个查询会出现一个问题,倘若有一个班级没有任何学生,那么那个班级的‘学生数’就会被统计为NULL
The result will be like this:
ClassAID | StudentNumber |
---|---|
1 | 3 |
2 | 4 |
3 | NULL |
4 | NULL |
So I hope to display 0 instead of NULL when the result is empty. The
code is as follows:
--这是一个统计查询:查询各个班都分别有多少学生
SELECT
[ClassAID] = C.AID
,[StudentNumber] = ISNULL(COUNT(S.AID),0)
FROM Class AS C
JOIN Student AS S ON S.ClassAID = C.AID
GROUP BY C.AID
So, the result is this:
ClassAID | StudentNumber |
---|---|
1 | 3 |
2 | 4 |
3 | 0 |
4 | 0 |