有没有办法添加空值行,替换为0?
理想情况下,我想显示所有月份的数据,如果没有数据,则将列数设置为零。
目前SQL查询不是返回空行,我得到这样的输出......
我正在使用下面的代码获取结果集:
SELECT
DATENAME(MONTH,A.Date) 'Month', COUNT(LateStatus) 'Count', 'Late' 'Type'
FROM
Attendance1 A
WHERE
A.EnrollId = '10000' AND A.Date BETWEEN '2016-01-01' AND '2016-08-31' AND LateStatus = 'L'
GROUP BY
DATENAME(MONTH,A.Date)
答案 0 :(得分:1)
使用递归CTE(动态制作日历表):
With Months(mon) As
(Select dateAdd(month, datediff(month, 365, getdate()), 0)
Union All
Select DateAdd(month, 1, mon) from Months
Where mon < getdate())
Select DATENAME(MONTH, m.mon ) 'Month',
COUNT(LateStatus) 'Count', 'Late' 'Type'
FROM months m
left join Attendance1 a
on a.Date between m.mon and dateadd(month, 1, m.mon)
and a.EnrollId = '10000'
and a.LateStatus = 'L'
GROUP BY DATENAME(MONTH, m.Mon)
一个更通用的函数,用于生成可用于任何表达式的整数范围,是:
create function dbo.NumberList (@start integer, @end integer)
returns table
as Return
(
With ints(aInt) As
(Select @start Union All
Select aInt + 1 From ints
Where aInt < @end)
Select aInt from ints
)
创建此功能后,您可以使用它动态创建任何类型的任何值范围:
从8个月前到3个月前的几个月
Select i.aInt, Dateadd(month, i.aInt,
DateAdd(month, datediff(month(0, getdate()), 0))
From dbo.NumberList(-8, -3) i
答案 1 :(得分:0)
假设您拥有所有月份的部分数据,您可以使用条件聚合执行此操作。也就是说,使用WHERE
将SELECT
条件移至CASE
:
SELECT DATENAME(MONTH,A.Date) as Mon,
SUM(CASE WHEN A.EnrollId = '10000' AND LateStatus = 'L'
THEN 1 ELSE 0
END) as cnt,
'Late' as 'Type'
FROM Attendance1 A
WHERE AND A.Date BETWEEN '2016-01-01' AND '2016-08-31'
GROUP BY DATENAME(MONTH, A.Date)
ORDER BY MIN(A.Date);
还有其他方法,通常涉及LEFT JOIN
。但如果能解决问题,这是最简单的。