sql - 如果 sql select except 语句的结果没有返回记录,如何获取值 0?
问题描述
我的 SQL except 语句有问题,在我的例子中,我选择了两列,一列可以有值,而其他列不能有,因为第一个 SQL 语句的计数等于 except 语句之后的第二个 SQL 的计数。
我得到的结果:
GroupId absences
1 3
预期结果
GroupId absences
1 3
2 0
在这种情况下我该怎么办?
select
groupId,
(case when groupId = null then 0 else COUNT(*) end) as absence
from (
select
groupId,
COUNT(*) as absences1
from (
select distinct
MONTh,
DAY,
e.groupId
from employee_c c,
holiday hl,
employee e,
groups,
Get_Calendar_Date(
DATEADD(MONTH, DATEDIFF(MONTH, 0, CAST(DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) AS datetime)) + @Month - 1, 0),
DATEADD(MONTH, DATEDIFF(MONTH, -1, CAST(DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) AS datetime)) + @Month-1, -1)
)
where DATENAME(DD, Weekday) IN (
select WorkingdayId+1
from timetable s,
groups ds,
grouptime de
where dd.groupId = ds.groupId
and dd.groupId = de.groupId
and s.timetableId = de.timetableId
and de.groupId = ds.groupdId)
and DATEPART(MM,hl.startDate) = @Month
and c.isActive=1
except
(select Month,
Day,
d.departmentId
from department d,
Get_Calendar_Date(
DATEADD(MONTH, DATEDIFF(MONTH, 0, CAST(DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) AS datetime)) + @Month - 1, 0),
DATEADD(MONTH, DATEDIFF(MONTH, -1, CAST(DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) AS datetime)) + @Month - 1, -1)
),
holiday hle,
employee_c c,
employee e
where datepart(MM,hle.startDate) = @Month
and cast(Date as date) between hle.startDate and hle.endDate
and c.isActive=1
and d.groupId =e.groupId
and c.employeeId=e.employeeId
and c.isActive=1
)
) sc
group by Month,Day,groupId
) s
group by groupId
解决方案
推荐阅读
- linux - 将数组传递给 SSH 连接
- android - Gradle 重复库没有省略
- reactjs - 更改 dropzone-material-ui 中的段落样式
- spring - Spring Boot 2.1.7 具有 tomcat-embed-core conflit
- mongodb - 如何使用对另一个集合的聚合查询结果更新/插入 mongodb 集合
- java - 核心 Java 中的字符串
- java - 如何在 python 或 java 中准确计算此文件的页面?
- java - 在Android中输入新子节点后如何删除最旧的子节点
- excel - Excel,拆分名称与多个名字或姓氏或中间名的单词
- hyperledger-fabric - 创建网络的结构网络