自过去4 小时以来,我一直在尝试找到解决方案
与上述答案相比,我认为我的答案性能低下,
create table #month
(
id [int] IDENTITY(1,1) NOT NULL,
[month] varchar(3)
)
DBCC CHECKIDENT(#month, RESEED, 1)
insert into #month
values
('Jan'),
('Feb'),
('Mar'),
('Apr'),
('May'),
('Jun'),
('Jul'),
('Aug'),
('Sep'),
('Oct'),
('Nov'),
('Dec')
declare @id int
set @id=1
declare @month varchar(3)
declare @sql nvarchar(max)
set @sql=''
declare @order varchar(3)
while (@id<13)
BEGIN
set @month=(select [month] from #month where id=@id)
set @order=CONVERT(varchar(3),@id)
set @sql=@sql+'insert into #display
(
[Month],
[COUNT(FA)],
[COUNT(TPA)],
[COUNT(Gift)],
[ORDER]
)
select '''+ @month +''' AS [Month],
(select
COUNT(CONVERT(VARCHAR(3), DATENAME(MM,Created_Date), 100))
from FA
where CONVERT(VARCHAR(3), DATENAME(MM,Created_Date), 100)='''+ @month +''') [COUNT(FA)],
(select
COUNT(CONVERT(VARCHAR(3), DATENAME(MM,Created_Date), 100))
from TPA
where CONVERT(VARCHAR(3), DATENAME(MM,Created_Date), 100)='''+ @month +''') [COUNT(TPA)],
(select
COUNT(CONVERT(VARCHAR(3), DATENAME(MM,Created_Date), 100))
from Gift
where CONVERT(VARCHAR(3), DATENAME(MM,Created_Date), 100)='''+ @month +''') [COUNT(Gift)],
'''+ @order + ''' [Order]
'
set @id=@id+1 --Incrementing the month
END
exec sp_executesql @sql
print @sql
select [MONTH],
[COUNT(FA)],
[COUNT(TPA)],
[COUNT(Gift)]
from #display
order by convert(int,[ORDER])