检索过去11个月的图表

时间:2018-10-16 10:20:56

标签: sql-server

我需要11月份和12月的最后11个月以及图表的当前月份,但是没有数据时看不到该月份。而且仍然被称为不应该的最后几年。

declare @TempTable TABLE
(
[Order] int,
[Month] nvarchar(3),
[Booked] int,
[Cancelled] int
)

declare @CurrentYear int = cast(substring(convert(varchar, getdate(), 23), 0,5) as int)
declare @CurrentMonth int = cast(substring(convert(varchar, getdate(), 1), 0,3) as int)

insert into @TempTable 
select
(@CurrentYear - substring(convert(varchar, A.CreatedAt, 23), 0,5)) * 11 + 
@CurrentMonth - cast(substring(convert(varchar,A.CreatedAt, 1),0,3) as int)
as 'Order',
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),
(@CurrentYear - substring(convert(varchar, A.CreatedAt, 23), 0,5)) * 11 +
@CurrentMonth - cast(substring(convert(varchar,A.CreatedAt, 1),0,3) as int)



select * from @TempTable WHERE [Order] <> (SELECT MAX([Order]) FROM @TempTable) Order By [Order] DESC

enter image description here

0 个答案:

没有答案