我如何获得所有月份从日期formssql?

我有表名’payroll’和以下数据

month , pay January , 1200 March , 1500 December , 2000 

我希望从存储过程的水晶报告中得到以下结果我想要一个显示此结果的SQL查询

 Janury , 1200 February , 000 March , 1500 April , 000 May , 000 June , 000 July , 000 August , 000 September , 000 October , 000 November , 000 December , 2000 

请帮忙进行查询。

提前致谢

您可以创建另一个包含所有12个月的表。 然后使用payroll表执行外部payroll

尝试更改您的查询 –

 SELECT [month], pay = ISNULL(pay, 0) FROM ( VALUES ('January'), ('February'), ('March'), ('April'), ('May'), ('June'), ('July'), ('August'), ('September'), ('October'), ('November'), ('December') ) t([month]) LEFT JOIN  ON .... 

在SQL Server中,您可以这样做:

 WITH Months AS ( SELECT 'January' AS MonthName UNION ALL SELECT 'February' UNION ALL SELECT 'March' ... ) SELECT Months.MonthName ,COALESCE(Payroll.Pay, 0) FROM Months LEFT JOIN Payroll ON Months.MonthName = Payroll.Month 

你可能需要这样的东西。

 declare @monthno int declare @month varchar(50) create table #month_tmp ( mont varchar(20) null,number int null) set @monthno = 1 while @monthno < 13 begin SET @month=DateName(Month,cast(@monthno as varchar) + '-01-2001') insert into #month_tmp select @month, 0 set @monthno = @monthno + 1 end select [month],pay from payroll union select mont,number from #month_tmp drop table #month_tmp