Select substring(convert(nvarchar, A.CreatedAt, 107), 0, 4) as 'Month',
COUNT(*) as 'Booked',
sum(cast(A.IsCancelled as int)) as 'Cancelled'
From ReservationTbl A
group by substring(convert(nvarchar, A.CreatedAt, 107), 0, 4)
如何获取图表上当年前几个月的数据? 如果一个月没有数据,该如何声明并过零?
答案 0 :(得分:0)
像艾伦·贝特尔森(Allan Bertelsen)所说;将年份和月份的where子句与getdate()一起使用
Select substring(convert(nvarchar, A.CreatedAt, 107), 0, 4) as 'Month',
COUNT(*) as 'Booked',
sum(cast(A.IsCancelled as int)) as 'Cancelled'
From ReservationTbl A
where YEAR(A.CreatedAt) = YEAR(getdate())
and MONTH(A.CreatedAt) <= MONTH(getdate())
group by substring(convert(nvarchar, A.CreatedAt, 107), 0, 4)
答案 1 :(得分:0)
在where子句中指定上个月和当前月份
Select substring(convert(nvarchar, A.CreatedAt, 107), 0, 4) as 'Month',
COUNT(*) as 'Booked',
sum(cast(A.IsCancelled as int)) as 'Cancelled'
From ReservationTbl A
where YEAR(A.CreatedAt) = YEAR(getdate())
and MONTH(A.CreatedAt)>= month(DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 1, 0)) and MONTH(A.CreatedAt) <= MONTH(getdate())
group by substring(convert(nvarchar, A.CreatedAt, 107), 0, 4)